如何在PostgreSQL上添加条件唯一索引 [英] How to add a conditional unique index on PostgreSQL

查看:158
本文介绍了如何在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 then product_id should be unique.
  • If variant_id has a value then combination of product_id and variant_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆