且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在mySql中的多个列上定义条件非空约束?

更新时间:2023-10-15 08:37:16

不幸的是,MySQL 不支持CHECK约束。它解析它们,然后默认丢弃约束,就像它对MyISAM表上的外键约束一样。它甚至不给你关于不支持的约束类型的警告,我认为这是一个不良的设计决策。

Unfortunately, MySQL does not support CHECK constraints. It parses them and then silently discards the constraint, just like it does for foreign key constraints on a MyISAM table. It doesn't even give you a warning about the unsupported constraint type, which I think is a bad design decision on their part.

这里有一个使用触发器的解决方案: / p>

Here's a solution using a trigger:

mysql> DELIMITER //
mysql> CREATE TRIGGER check_one_not_null BEFORE INSERT ON mytable FOR EACH ROW 
    IF COALESCE(NEW.D, NEW.E, NEW.F) IS NULL 
    THEN SIGNAL SQLSTATE '45000' 
      SET MESSAGE_TEXT = 'One of D, E, or F must have a non-null value.';
    END IF //

您还应该创建一个类似的触发器 BEFORE UPDATE

You should also create a similar trigger BEFORE UPDATE on the same table.

请参阅 http://dev.mysql.com/doc/refman/5.6/en/signal.html 了解有关 SIGNAL的更多信息用于在MySQL触发器或存储例程中引发异常的语句。

See http://dev.mysql.com/doc/refman/5.6/en/signal.html for more information on the SIGNAL statement to raise exceptions in MySQL triggers or stored routines.