Can I have a constraint on count of distinct values in a column in SQL?

岁酱吖の 提交于 2019-12-10 17:09:49

问题


Table: Relatives

  • emp_id
  • dep_id(composite primary key)

We have to restrict one employee to three dependents.


回答1:


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;

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;



回答2:


Add an new integer not null column occurrence, add a check constraint occurrence BETWEEN 1 AND 3, add a unique constraint on the compound of emp_id and occurrence, optionally add helper procs to maintain occurrence values.



来源:https://stackoverflow.com/questions/8770552/can-i-have-a-constraint-on-count-of-distinct-values-in-a-column-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!