postgresql - 引用继承表的外键

标签 postgresql postgresql-9.2

我有以下表格:

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);

incomingoutgoing 继承自 mail 并再次定义它们的外键(和主键),因为它们不会自动继承。

问题是:

如果我要插入一封 incoming 邮件,则不可能从 outgoing 表中引用它,因为外键只适用于 super 表(邮件).

有解决办法吗?

最佳答案

PostgreSQL 9.3 docs :

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/

相关文章:

django - 如何执行计数并加入django?

sql - 如何使用扩展 pg_trgm 中的 % 运算符?

postgresql - 如何删除 Postgres 9.2 中的死行版本

gem - 错误无法在本地 Windows 7 Ruby on Rails 上加载 'pg' gem

python - 预取列序列 SQLAlchemy

postgresql - Postgres 9.2 pg_largeobject 表空间

ruby-on-rails - 如何使用共享数据库在 Heroku 上进行 GIS 查询?

ruby-on-rails - 将数据库更改为 Postgres,现在 Rspec 抛出错误 : can't find object by id

ruby - 从 ActiveRecord 原始 SQL 获取类型化结果

postgresql - 如何读取PostgreSQL wal文件数据?是否有任何命令可以将 PostgreSQL 二进制文件转换为可读文本格式?