《MYSQL教程mysql 中存在null和空時創建唯一索引的方法》要點:
本文介紹了MYSQL教程mysql 中存在null和空時創建唯一索引的方法,希望對您有用。如果有疑問,可以聯系我們。
MYSQL學習好多情況下數據庫默認值都有null,但是經過程序處理很多時候會出現,數據庫值為空而不是null的情況.此時創建唯一索引時要注意了,此時數據庫會把空作為多個重復值,而創建索引失敗,示例如下:
MYSQL學習步調1:
MYSQL學習mysql> select phone ,count(1) from User group by phone;
+-----------------+----------+
| phone | count(1) |
+-----------------+----------+
| NULL | 70 |
| | 40 |
| +86-13390889711 | 1 |
| +86-13405053385 | 1 |
MYSQL學習步調一中發現數據庫中有70條null數據,有40條為空的數據.
MYSQL學習步調2:
MYSQL學習mysql> select count(1) from User where phone is null;
+----------+
| count(1) |
+----------+
| 70 |
+----------+
1 row in set (0.00 sec)
MYSQL學習經2再次驗證數據庫中null和空紛歧樣的兩個值.
MYSQL學習步調3:
MYSQL學習mysql> alter table User add constraint uk_phone unique(phone);
ERROR 1062 (23000): Duplicate entry '' for key 'uk_phone'
此時創建索引提示‘ '為一個重復的屬性.
MYSQL學習步調4:將所有的空值改成null
MYSQL學習mysql> update User set phone = NULL where phone = '';
Query OK, 40 rows affected (0.11 sec)
Rows matched: 40 Changed: 40 Warnings: 0
步調5:再次創建唯一索引
MYSQL學習mysql> alter table User add constraint uk_phone unique(phone);
Query OK, 0 rows affected (0.34 sec)
Records: 0 Duplicates: 0 Warnings: 0
MYSQL學習創建勝利,OK了
歡迎參與《MYSQL教程mysql 中存在null和空時創建唯一索引的方法》討論,分享您的想法,維易PHP學院為您提供專業教程。