有条件时添加唯一列
Add unique column when I have condition
我有table这些是table
的字段
project_labor
PROJECT_NO, LABOR_ID, STATUS
状态字段有两个值(完整或完整)
如果status的值为(complete) labor id可以重复
但如果状态值为(不完整),则 labor id 必须是唯一的
您可以使用函数索引(默认情况下 NULL
跳过单列索引的值):
CREATE UNIQUE INDEX IX_name
ON project_labor (CASE WHEN STATUS='complete' THEN NULL ELSE LABOR_ID END);
完整脚本:
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
我有table这些是table
的字段project_labor
PROJECT_NO, LABOR_ID, STATUS
状态字段有两个值(完整或完整)
如果status的值为(complete) labor id可以重复
但如果状态值为(不完整),则 labor id 必须是唯一的
您可以使用函数索引(默认情况下 NULL
跳过单列索引的值):
CREATE UNIQUE INDEX IX_name
ON project_labor (CASE WHEN STATUS='complete' THEN NULL ELSE LABOR_ID END);
完整脚本:
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