繁体   English   中英

跨表的Postgres唯一组合约束

[英]Postgres unique combination constraint across tables

我有三张桌子-

file (
  file_id int primary key
  filename text not null
  etc...
)
product (
  product_id int primary key
  etc....
)
product_attachment (
  product_id references product
  file_id references file
)

我想确保当它们自然连接时,product_id + filename是唯一的。 到目前为止,我拥有的最佳解决方案是将文件名添加到product_attachment表中,但是我想知道是否有避免这种情况的方法。

如果文件名列不是唯一的,则可以在product_attachment表上添加自定义约束。 请注意,这将在每次插入和更新时执行以下查询,这并不是理想的性能。

CREATE OR REPLACE FUNCTION check_filename(product_id integer, file_id integer)
RETURNS boolean AS
$$
    LOCK product_attachment IN SHARE MODE;
    SELECT (COUNT(*) = 0)
    FROM product_attachment pa
    JOIN file f1 ON f1.file_id = pa.file_id
    JOIN file f2 ON f1.filename = f2.filename
    WHERE pa.product_id = $1 AND f2.file_id = $2
$$
LANGUAGE 'plpgsql'

ALTER TABLE product_attachment
ADD CONSTRAINT check_filename CHECK
(check_filename(product_id, file_id))

为什么不只是向product_attachment添加唯一约束?

create unique index idx_product_attachment_2 on product_attachment(product_id, file_id);

这假定文件名是唯一的,您可以通过将文件名定义为该表中的唯一名称来确保这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM