Unique key with NULLs

前端 未结 10 806
一整个雨季
一整个雨季 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:28

    The perfect solution would be support for function based UK's, but that becomes more complex as mySQL would also then need to support function based indexes. This would prevent the need to use "fake" values in place of NULL, while also allowing developers the ability to decide how to treat NULL values in UK's. Unfortunately, mySQL doesn't currently support such functionality that I am aware of, so we're left with workarounds.

    CREATE TABLE employee( 
     name CHAR(50) NOT NULL, 
     date_of_birth DATE, 
     title CHAR(50), 
     UNIQUE KEY idx_name_dob (name, IFNULL(date_of_birth,'0000-00-00 00:00:00'))
    );
    

    (Note the use of the IFNULL() function in the unique key definition)

提交回复
热议问题