我有表格,这些是表格的字段
project_labor
PROJECT_NO, LABOR_ID, STATUS
状态字段具有两个值(完整或不完整)
如果状态值是(完整),则可以重复劳动编号
但是如果状态值为(不完整),则劳工编号必须是唯一的
答案 0 :(得分:2)
您可以使用函数索引(默认情况下,单列索引的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