Either OR non-null constraints in MySQL

前端 未结 6 1518
忘了有多久
忘了有多久 2021-02-05 23:06

What\'s the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can\'t both be NULL. I don\'t care if either one is NULL by itself, just as long as the

6条回答
  •  醉话见心
    2021-02-05 23:25

    @Sklivvz: Testing with MySQL 5.0.51a, I find it parses a CHECK constraint, but does not enforce it. I can insert (NULL, NULL) with no error. Tested both MyISAM and InnoDB. Subsequently using SHOW CREATE TABLE shows that a CHECK constraint is not in the table definition, even though no error was given when I defined the table.

    This matches the MySQL manual which says: "The CHECK clause is parsed but ignored by all storage engines."

    So for MySQL, you would have to use a trigger to enforce this rule. The only problem is that MySQL triggers have no way of raising an error or aborting an INSERT operation. One thing you can do in the trigger to cause an error is to set a NOT NULL column to NULL.

    CREATE TABLE foo (
      FieldA INT,
      FieldB INT,
      FieldA_or_FieldB TINYINT NOT NULL;
    );
    
    DELIMITER //
    CREATE TRIGGER FieldABNotNull BEFORE INSERT ON foo
    FOR EACH ROW BEGIN
      IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN
        SET NEW.FieldA_or_FieldB = NULL;
      ELSE
        SET NEW.FieldA_or_FieldB = 1;
      END IF;
    END//
    
    INSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK
    INSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK
    INSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error
    

    You also need a similar trigger BEFORE UPDATE.

提交回复
热议问题