2

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

4

2 回答 2

0

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

ALTER TABLE TableName
ADD CONSTRAINT AB UNIQUE (A,B)
于 2013-08-03T17:02:13.010 回答
0

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

我找到了 Roland Bouman 的这个解决方案。根据他的解决方案的精神,这就是我所拥有的:

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;
于 2013-08-03T17:15:38.123 回答