好多情況下數(shù)據(jù)庫(kù)默認(rèn)值都有null,但是經(jīng)過(guò)程序處理很多時(shí)候會(huì)出現(xiàn),數(shù)據(jù)庫(kù)值為空而不是null的情況。此時(shí)創(chuàng)建唯一索引時(shí)要注意了,此時(shí)數(shù)據(jù)庫(kù)會(huì)把空作為多個(gè)重復(fù)值,而創(chuàng)建索引失敗,示例如下:
步驟1:
mysql> select phone ,count(1) from user group by phone;
+-----------------+----------+
| phone | count(1) |
+-----------------+----------+
| null | 70 |
| | 40 |
| +86-13390889711 | 1 |
| +86-13405053385 | 1 |
步驟一中發(fā)現(xiàn)數(shù)據(jù)庫(kù)中有70條null數(shù)據(jù),有40條為空的數(shù)據(jù)。
步驟2:
mysql> select count(1) from user where phone is null;
+----------+
| count(1) |
+----------+
| 70 |
+----------+
1 row in set (0.00 sec)
經(jīng)2再次驗(yàn)證數(shù)據(jù)庫(kù)中null和空不一樣的兩個(gè)值。
步驟3:
mysql> alter table user add constraint uk_phone unique(phone);
error 1062 (23000): duplicate entry '' for key 'uk_phone'
此時(shí)創(chuàng)建索引提示‘ '為一個(gè)重復(fù)的屬性。
步驟4:將所有的空值改成null
mysql> update user set phone = null where phone = '';
query ok, 40 rows affected (0.11 sec)
rows matched: 40 changed: 40 warnings: 0
步驟5:再次創(chuàng)建唯一索引
mysql> alter table user add constraint uk_phone unique(phone);
query ok, 0 rows affected (0.34 sec)
records: 0 duplicates: 0 warnings: 0
創(chuàng)建成功,ok了
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄