Unique key with NULLs

前端 未结 10 853
一整个雨季
一整个雨季 2020-12-03 00:48

This question requires some hypothetical background. Let\'s consider an employee table that has columns name, date_of_birth, tit

10条回答
  •  感情败类
    2020-12-03 01:08

    I recommend to create additional table column checksum which will contain md5 hash of name and date_of_birth. Drop unique key (name, date_of_birth) because it doesn't solve the problem. Create one unique key on checksum.

    ALTER TABLE employee 
        ADD COLUMN checksum CHAR(32) NOT NULL;
    
    UPDATE employee 
    SET checksum = MD5(CONCAT(name, IFNULL(date_of_birth, '')));
    
    ALTER TABLE employee 
        ADD UNIQUE (checksum);
    

    This solution creates small technical overhead, cause for every inserted pairs you need to generate hash (same thing for every search query). For further improvements you can add trigger that will generate hash for you in every insert:

    CREATE TRIGGER before_insert_employee 
    BEFORE INSERT ON employee
    FOR EACH ROW
        IF new.checksum IS NULL THEN
          SET new.checksum = MD5(CONCAT(new.name, IFNULL(new.date_of_birth, '')));
        END IF;
    

提交回复
热议问题