我有以下表格:
CREATE TABLE mail (
id serial,
parent_mail_id integer,
...
PRIMARY KEY (id),
FOREIGN KEY (parent_mail_id) REFERENCES mail(id),
...
);
CREATE TABLE incoming (
from_contact_id integer NOT NULL REFERENCES contact(id),
...
PRIMARY KEY (id),
---> FOREIGN KEY (parent_mail_id) REFERENCES mail(id), <---
...
) INHERITS(mail);
CREATE TABLE outgoing (
from_user_id integer NOT NULL REFERENCES "user"(id),
...
PRIMARY KEY (id),
--> FOREIGN KEY (parent_mail_id) REFERENCES mail(id), <--
...
) INHERITS(mail);
incoming
和 outgoing
继承自 mail
并再次定义它们的外键(和主键),因为它们不会自动继承。
问题是:
如果我要插入一封 incoming
邮件,则不可能从 outgoing
表中引用它,因为外键只适用于 super 表(邮件
).
有解决办法吗?
最佳答案
A serious limitation of the inheritance feature is that indexes (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. Thus, in the terms of the above example:
If we declared cities.name to be UNIQUE or a PRIMARY KEY, this would not stop the capitals table from having rows with names duplicating rows in cities. And those duplicate rows would by default show up in queries from cities. In fact, by default capitals would have no unique constraint at all, and so could contain multiple rows with the same name. You could add a unique constraint to capitals, but this would not prevent duplication compared to cities.
Similarly, if we were to specify that cities.name REFERENCES some other table, this constraint would not automatically propagate to capitals. In this case you could work around it by manually adding the same REFERENCES constraint to capitals.
Specifying that another table's column REFERENCES cities(name) would allow the other table to contain city names, but not capital names. There is no good workaround for this case.
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.
这并不是真正的解决方法,所以也许可以将 mails 设为非继承表,然后将 incoming_columns 和 outgoing_columns 分开作为它们各自的额外列,并将邮件 ID 作为它们的主键和外键。例如,您可以创建一个作为邮件发送的 View INNER JOIN outgoing_columns。
关于postgresql - 引用继承表的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18023559/