我可以限制SQL列中不同值的计数吗? [英] Can I have a constraint on count of distinct values in a column in SQL?
本文介绍了我可以限制SQL列中不同值的计数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
表格:亲戚
-
emp_id
-
dep_id
(复合主键)
emp_id
dep_id
(composite primary key)
我们必须将一名雇员限制为三名家属.
We have to restrict one employee to three dependents.
推荐答案
This cannot be done using a check constraint alone, but there is a way using a materialized view and a check constraint as I demonstrate here on my blog. For your example this would be:
create materialized view emp_dep_mv
build immediate
refresh complete on commit as
select emp_id, count(*) cnt
from relatives
group by emp_id;
alter table emp_dep_mv
add constraint emp_dep_mv_chk
check (cnt <= 3)
deferrable;
但是,这种方法在大型,繁忙的生产数据库中可能无法执行,在这种情况下,您可以采用使用触发器和检查约束以及employees表中的额外列的方法:
However, this approach might not be performant in a large, busy production database, in which case you could go for an approach that uses triggers and a check constraint, plus an extra column on the employees table:
alter table employees add num_relatives number(1,0) default 0 not null;
-- Populate for existing data
update employees
set num_relatives = (select count(*) from relatives r
where r.emp_id = e.emp_id)
where exists (select * from relatives r
where r.emp_id = e.emp_id);
alter table employees add constraint emp_relatives_chk
check (num_relatives <= 3);
create trigger relatives_trg
after insert or update or delete on relatives
for each row
begin
if inserting or updating then
update employees
set num_relatives = num_relatives + 1
where emp_id = :new.emp_id;
end if;
if deleting or updating then
update employees
set num_relatives = num_relatives - 1
where emp_id = :old.emp_id;
end if;
end;
这篇关于我可以限制SQL列中不同值的计数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文