简体   繁体   English

我可以对SQL中的列中的不同值的计数进行约束吗?

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

Table: Relatives 表: 亲戚

  • emp_id
  • dep_id (composite primary key) dep_id (复合主键)

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;

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: 但是,这种方法在大型繁忙的生产数据库中可能无法实现,在这种情况下,您可以使用触发器和检查约束的方法,以及employees表上的额外列:

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;

添加一个新的整数非空列occurrence ,添加一个检查约束, occurrence BETWEEN 1 AND 3 ,在emp_idoccurrence的复合上添加一个唯一约束,可选择添加辅助过程来维护occurrence值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM