MySQL:两个字段中至少有一个的约束

时间:2013-08-03 16:46:07

标签: mysql sql foreign-keys constraints foreign-key-relationship

我的表由两列组成:A和B,它们都可以为空,是来自其他表的外键。如何施加约束,使A或B中至少有一个不为空?

2 个答案:

答案 0 :(得分:0)

您可以使A和B不为空(但零可以)并在两列上添加唯一键:

ALTER TABLE TableName
ADD CONSTRAINT AB UNIQUE (A,B)

答案 1 :(得分:0)

可能的答案:如果有更好的解决方案,请提供意见。

我找到了Roland Bouman的this解决方案。基于他的解决方案的精神,这就是我所拥有的:

delimiter go

create procedure validateAtLeastOneValue(
    in a bigint(16), in b bigint(16)
)
deterministic
no sql
_main: begin
    declare err_no value_specified condition for sqlstate '45000';

    if a is not null then
        leave _main; -- nothing to validate
    end if;
    if b is not null then
        leave _main; -- nothing to validate
    end if;
    signal err_no_value_specified -- raise an error
    set message_text = 'No value specified';
end;
go

delimiter ;

现在从事件处理程序调用此过程以在表上插入(或更新)。

create trigger on_before_insert
before insert on mytable
for each row
begin
    call validateAtLeastOneType(
        NEW.a
    ,   NEW.b 
    );
end;

create trigger on_before_update
before update on mytable
for each row
begin
    call validateAtLeastOneType(
        NEW.a
    ,   NEW.b 
    );
end;