mysql 中存在null和空時創(chuàng)建唯一索引的方法
好多情況下數(shù)據(jù)庫默認(rèn)值都有null,但是經(jīng)過程序處理很多時候會出現(xiàn),數(shù)據(jù)庫值為空而不是null的情況。此時創(chuàng)建唯一索引時要注意了,此時數(shù)據(jù)庫會把空作為多個重復(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ù)庫中有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再次驗證數(shù)據(jù)庫中null和空不一樣的兩個值。
步驟3:
mysql> alter table User add constraint uk_phone unique(phone);
ERROR 1062 (23000): Duplicate entry '' for key 'uk_phone'
此時創(chuàng)建索引提示‘ '為一個重復(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了
相關(guān)文章
Mysql將查詢結(jié)果集轉(zhuǎn)換為JSON數(shù)據(jù)的實例代碼
這篇文章主要介紹了Mysql將查詢結(jié)果集轉(zhuǎn)換為JSON數(shù)據(jù)的實例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03mysql通過find_in_set()函數(shù)實現(xiàn)where in()順序排序
這篇文章主要介紹了mysql通過find_in_set()函數(shù)實現(xiàn)where in()順序排序的相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。2017-10-10DBeaver連接mysql和oracle數(shù)據(jù)庫圖文教程
DBeaver是一款免費的數(shù)據(jù)庫管理工具,支持多種數(shù)據(jù)庫,包括MySQL,下面這篇文章主要給大家介紹了關(guān)于DBeaver連接mysql和oracle數(shù)據(jù)庫的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05