我有一个问题,我可以说我有一个由学生表和教师表继承的人员表.如果我执行INSERT INTO学生和INSERT INTO教师并指定人员表(P_Id)的主键,例如
INSERT INTO student(P_Id,LastName,FirstName,StudentNumber) VALUES (1,'Jones','Casey','SID0001'); INSERT INTO teacher(P_Id,FacultyNumber) VALUES (1,'JONES0001');@H_404_4@我结束了我的人员表中的两个重复记录(P_Id是我在人员表上的主键)看起来子表正在插入人员表而不考虑该表上的约束.人员表上的主键约束是否应该阻止创建重复记录? @H_404_4@我已经考虑使用触发器解决此问题,该触发器将在人员表上进行插入之前触发,该表将检查已存在的P_Id.但我希望它能阻止我做这些事情,或者我希望它只在子表中智能地创建记录 @H_404_4@执行此操作后,如果在学生表中更改LastName并将更改反映到教师表中,则会出现问题吗? @H_404_4@以下是创建语句,上面的Insert语句仅用于举例说明,我知道它们不能用于创建的这些表:
CREATE TABLE people ( people_id integer NOT NULL,last_name character varying NOT NULL,first_name character varying NOT NULL,middle_name character varying,gender character varying NOT NULL,date_of_birth date,ssn character varying,pref_language character varying,CONSTRAINT people_pkey PRIMARY KEY (people_id) ) CREATE TABLE student ( -- Inherited from table people: people_id integer NOT NULL,-- Inherited from table people: last_name character varying NOT NULL,-- Inherited from table people: first_name character varying NOT NULL,-- Inherited from table people: middle_name character varying,-- Inherited from table people: gender character varying NOT NULL,-- Inherited from table people: date_of_birth date,-- Inherited from table people: ssn character varying,-- Inherited from table people: pref_language character varying,student_id integer NOT NULL,race character varying(80),ethnicity character varying(80),employer character varying(80),school character varying(80),pref_location character varying(80),CONSTRAINT student_pkey PRIMARY KEY (student_id) ) INHERITS (people) CREATE TABLE teacher ( -- Inherited from table people: people_id integer NOT NULL,teacher_id integer NOT NULL,user_name character varying NOT NULL,"password" character varying NOT NULL,title character varying,CONSTRAINT teacher_pkey PRIMARY KEY (teacher_id) ) INHERITS (people)
解决方法
我认为这种行为是设计的.从
PostgreSQL docs. . .
@H_404_4@INSERT always inserts into exactly the table specified.@H_404_4@而且,在页面稍远一点. . .
@H_404_4@All check constraints and not-null constraints on a parent table are@H_404_4@如果您只选择人,则不会看到任何行.如果您只选择学生,您会看到多行具有相同的people_id.也就是说,您可以向学生插入具有相同person_id值的多行.这充其量是违反直觉的;文档说它已经坏了,但有一天可能会被修复. @H_404_4@来自“警告”部分. . .
automatically inherited by its children. Other types of constraints
(unique,primary key,and foreign key constraints) are not inherited.
@H_404_4@A serIoUs limitation of the inheritance feature is that indexes@H_404_4@同一节.
(including unique constraints) and foreign key constraints only apply
to single tables,not to their inheritance children. This is true on
both the referencing and referenced sides of a foreign key constraint.
@H_404_4@These deficiencies will probably be fixed in some future release,but in the meantime considerable care is needed in deciding whether inheritance is useful for your application.