我正在写一个表,如果 B 不为空,我需要 A 不为空(见下文)。我正在尝试写一张支票,但我不确定如何写。非常感谢任何建议。
CREATE TABLE `Test`
`A` varchar(4) CHECK(?),
`B` varchar(4)
);
最佳答案
不要为 CHECK
约束而烦恼。根据the manual :
The
CHECK
clause is parsed but ignored by all storage engines.
您可以改为使用触发器,如 this thread 中所建议的那样.测试本身就是
(B is null) or (A is not null)
编辑:假设您使用的是 MySQL 5.5 或更高版本,下面是您如何在违反条件时触发错误信号:
mysql> DELIMITER //
mysql> DROP TRIGGER IF EXISTS before_insert_trigger//
mysql> CREATE TRIGGER before_insert_trigger
-> BEFORE INSERT ON Customer FOR EACH ROW
-> BEGIN
-> DECLARE msg VARCHAR(255);
-> IF (NEW.B is not null) and (NEW.A is null) THEN
-> SET msg = concat('Error: Trying to insert a NULL A when B is not null: ',
-> cast(NEW.B as char));
-> SIGNAL sqlstate '45000' SET message_text = msg;
-> END IF;
-> END//
mysql> delimiter ;
(注意我把测试倒过来是因为我想在违反的时候测试,而不是在满足的时候测试。)如果你使用的是早期版本的MySQL,你可以使用this answer中提供的建议。或 here .
关于mysql - 如果其他条目不为空,则不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31927584/