2

我的表由兩列組成:A和B,它們都是可以爲空的,並且是來自其他表的外鍵。我該如何施加一個約束,即A或B中至少有一個不應該爲空?MySQL:兩個字段中的至少一個的約束

+0

MySQL根本不支持檢查約束。 [從文檔](http://dev.mysql.com/doc/refman/5.1/en/create-table.html)「CHECK子句已解析,但被所有存儲引擎忽略。」 – Andomar

+0

刪除了答案,我沒有意識到你正在使用MySQL。 – ClaireG

+0

如果它們是外鍵,這是否意味着您有其他具有可空主鍵的表?這聽起來不對。 –

回答

0

可能的答案:請提供意見,如果有一個更好的解決方案。

我發現this由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; 
0

可以使A和B不爲空(但零是確定),並在兩列添加一個唯一的密鑰:

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

但是這會對A B施加唯一性作爲組合,對嗎?這不是我想要的。 – Neel

+1

正確,如果您想要在多個記錄上使用相同的組合,則不太好。 – Pierre

相關問題