有条件时添加唯一列

时间:2019-06-13 18:23:30

标签: sql oracle unique-index

我有表格,这些是表格的字段

project_labor
PROJECT_NO, LABOR_ID, STATUS

状态字段具有两个值(完整或不完整)
如果状态值是(完整),则可以重复劳动编号
但是如果状态值为(不完整),则劳工编号必须是唯一的

1 个答案:

答案 0 :(得分:2)

您可以使用函数索引(默认情况下,单列索引的NULL值将被跳过):

CREATE UNIQUE INDEX IX_name 
ON project_labor (CASE WHEN STATUS='complete' THEN NULL ELSE LABOR_ID END);

db<>fiddle demo

完整脚本:

CREATE TABLE project_labor(PROJECT_NO INT, LABOR_ID INT, STATUS VARCHAR2(10));

CREATE UNIQUE INDEX IX_name 
ON project_labor (CASE WHEN STATUS='complete' THEN NULL ELSE labor_id END);

INSERT INTO project_labor(project_no,status,labor_id) VALUES(1, 'uncomplete', 1);
INSERT INTO project_labor(project_no,status,labor_id) VALUES(2, 'uncomplete', 1);
-- ORA-00001: unique constraint (IX_NAME) violated

INSERT INTO project_labor(project_no,status,labor_id) VALUES(3, 'complete', 2)
INSERT INTO project_labor(project_no,status,labor_id) VALUES(4, 'complete', 2)

SELECT * FROM project_labor

它等效于其他RDBMS的部分索引:

PostgreSQL - partial index / SQLite - Partial index / SQL Server - filtered index