Either OR non-null constraints in MySQL

前端 未结 6 1534
忘了有多久
忘了有多久 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:23

    I accomplished this using a GENERATED ALWAYS column with COALESCE ... NOT NULL:

    DROP TABLE IF EXISTS `error`;
    
    CREATE TABLE IF NOT EXISTS `error` (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        left_id BIGINT UNSIGNED NULL,
        right_id BIGINT UNSIGNED NULL,
        left_or_right_id BIGINT UNSIGNED GENERATED ALWAYS AS (COALESCE(left_id, right_id)) NOT NULL,
        when_occurred TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        message_text LONGTEXT NOT NULL,
        INDEX id_index (id),
        INDEX when_occurred_index (when_occurred),
        INDEX left_id_index (left_id),
        INDEX right_id_index (right_id)
    );
    
    INSERT INTO `error` (left_id, right_id, message_text) VALUES (1, 1, 'Some random text.');  -- Ok.
    INSERT INTO `error` (left_id, right_id, message_text) VALUES (null, 1, 'Some random text.'); -- Ok.
    INSERT INTO `error` (left_id, right_id, message_text) VALUES (1, null, 'Some random text.'); -- Ok.
    INSERT INTO `error` (left_id, right_id, message_text) VALUES (null, null, 'Some random text.'); -- ER_BAD_NULL_ERROR: Column 'left_or_right_id' cannot be null
    

    on MySQL version 8.0.22

提交回复
热议问题