将值的计数限制为每组一个
Constraint to limit count of value to one per group
我有一个 table 和一个 Employee_ID、Position_ID 和 Active_Status。 Employee_ID和Position_ID都是外键,也是这个table中的组合键。一名员工可以担任多个职位,但他们在任何给定时间都不应拥有超过一个活跃职位。是否有可以实现此限制的约束?
下面的代码显然不正确,但类似于,
CONSTRAINT chkStatus CHECK ((SELECT COUNT(ACTIVE) FROM EMPLOYEE_DETAIL WHERE ACTIVE = 'Y' GROUP BY EMPLOYEE_ID) = 1)
任何主要 RDBMS 都不支持多行检查约束(又名断言)。
SQL Assertions / Declarative multi-row constraints
您可以使用 filtered/partial UNIQUE
索引:
CREATE UNIQUE INDEX idx ON EMPLOYEE_DETAIL(Employee_id) WHERE ACTIVE = 'Y';
A partial index definition may include the UNIQUE keyword. If it does, then SQLite requires every entry in the index to be unique. This provides a mechanism for enforcing uniqueness across some subset of the rows in a table.
我有一个 table 和一个 Employee_ID、Position_ID 和 Active_Status。 Employee_ID和Position_ID都是外键,也是这个table中的组合键。一名员工可以担任多个职位,但他们在任何给定时间都不应拥有超过一个活跃职位。是否有可以实现此限制的约束?
下面的代码显然不正确,但类似于,
CONSTRAINT chkStatus CHECK ((SELECT COUNT(ACTIVE) FROM EMPLOYEE_DETAIL WHERE ACTIVE = 'Y' GROUP BY EMPLOYEE_ID) = 1)
任何主要 RDBMS 都不支持多行检查约束(又名断言)。
SQL Assertions / Declarative multi-row constraints
您可以使用 filtered/partial UNIQUE
索引:
CREATE UNIQUE INDEX idx ON EMPLOYEE_DETAIL(Employee_id) WHERE ACTIVE = 'Y';
A partial index definition may include the UNIQUE keyword. If it does, then SQLite requires every entry in the index to be unique. This provides a mechanism for enforcing uniqueness across some subset of the rows in a table.