mysql 中存在null和空時創(chuàng)建唯一索引的方法
來源:易賢網 閱讀:1409 次 日期:2014-12-10 11:59:20
溫馨提示:易賢網小編為您整理了“mysql 中存在null和空時創(chuàng)建唯一索引的方法”,方便廣大網友查閱!

好多情況下數據庫默認值都有null,但是經過程序處理很多時候會出現,數據庫值為空而不是null的情況。此時創(chuàng)建唯一索引時要注意了,此時數據庫會把空作為多個重復值,而創(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ā)現數據庫中有70條null數據,有40條為空的數據。

步驟2:

mysql> select count(1) from user where phone is null;

+----------+

| count(1) |

+----------+

| 70 |

+----------+

1 row in set (0.00 sec)

經2再次驗證數據庫中null和空不一樣的兩個值。

步驟3:

mysql> alter table user add constraint uk_phone unique(phone);

error 1062 (23000): duplicate entry '' for key 'uk_phone'

此時創(chuàng)建索引提示‘ '為一個重復的屬性。

步驟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了

更多信息請查看IT技術專欄

更多信息請查看數據庫
關于我們 | 聯系我們 | 人才招聘 | 網站聲明 | 網站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點

版權所有:易賢網