如何在PostgreSQL上添加条件唯一索引 [英] How to add a conditional unique index on PostgreSQL
问题描述
我有一个 line_items
表,其中包含以下列:
I have a line_items
table with following columns:
product_id
variant_id
variant_id
可以为空。
以下是条件:
- 如果
variant_id
为NULL,然后product_id
应该是唯一的。 - 如果
variant_id
有一个值,那么product_id
和<$ c的组合$ c> variant_id 应该是唯一的。
- If
variant_id
is NULL thenproduct_id
should be unique. - If
variant_id
has a value then combination ofproduct_id
andvariant_id
should be unique.
这是否可以在PostgreSQL中使用?
Is that possible in PostgreSQL?
推荐答案
创建上的nofollow noreferrer> UNIQUE
多列索引(product_id,variant_id):
CREATE UNIQUE INDEX line_items_prod_var_idx ON line_items (product_id, variant_id);
但是,这将允许(1,NULL)的多个条目
for (product_id,variant_id)
因为 NULL
值不相同。
为了弥补这一点,另外创建一个部分 UNIQUE
索引 product_id
:
However, this would allow multiple entries of (1, NULL)
for (product_id, variant_id)
because NULL
values are not considered identical.
To make up for that, additionally create a partial UNIQUE
index on product_id
:
CREATE UNIQUE INDEX line_items_prod_var_null_idx ON line_items (product_id)
WHERE variant_id IS NULL;
这样你就可以输入(1,2)
,(1,3)
和(1,NULL)
,但它们都不是第二次。同时加快一栏或两栏条件的查询速度。
This way you can enter (1,2)
, (1,3)
and (1, NULL)
, but neither of them a second time. Also speeds up queries with conditions on one or both column.
最近,dba.SE上的相关答案,几乎直接适用于你的案例:
Recent, related answer on dba.SE, almost directly applicable to your case:
- PostgreSQL multi-column unique constraint and NULL values
这篇关于如何在PostgreSQL上添加条件唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!