Either OR non-null constraints in MySQL

前端 未结 6 1540
忘了有多久
忘了有多久 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条回答
  •  猫巷女王i
    2021-02-05 23:12

    MySQL 5.5 introduced SIGNAL, so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too.

    CREATE TABLE foo (
      FieldA INT,
      FieldB INT
    );
    
    DELIMITER //
    CREATE TRIGGER InsertFieldABNotNull BEFORE INSERT ON foo
    FOR EACH ROW BEGIN
      IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null';
      END IF;
    END//
    CREATE TRIGGER UpdateFieldABNotNull BEFORE UPDATE ON foo
    FOR EACH ROW BEGIN
      IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null';
      END IF;
    END//
    DELIMITER ;
    
    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
    UPDATE foo SET FieldA = NULL; -- gives error
    

提交回复
热议问题