《MYSQL教程mysql 中存在null和空時(shí)創(chuàng)建唯一索引的方法》要點(diǎn):
本文介紹了MYSQL教程mysql 中存在null和空時(shí)創(chuàng)建唯一索引的方法,希望對您有用。如果有疑問,可以聯(lián)系我們。
MYSQL學(xué)習(xí)好多情況下數(shù)據(jù)庫默認(rèn)值都有null,但是經(jīng)過程序處理很多時(shí)候會(huì)出現(xiàn),數(shù)據(jù)庫值為空而不是null的情況.此時(shí)創(chuàng)建唯一索引時(shí)要注意了,此時(shí)數(shù)據(jù)庫會(huì)把空作為多個(gè)重復(fù)值,而創(chuàng)建索引失敗,示例如下:
MYSQL學(xué)習(xí)步調(diào)1:
MYSQL學(xué)習(xí)mysql> select phone ,count(1) from User group by phone;
+-----------------+----------+
| phone | count(1) |
+-----------------+----------+
| NULL | 70 |
| | 40 |
| +86-13390889711 | 1 |
| +86-13405053385 | 1 |
MYSQL學(xué)習(xí)步調(diào)一中發(fā)現(xiàn)數(shù)據(jù)庫中有70條null數(shù)據(jù),有40條為空的數(shù)據(jù).
MYSQL學(xué)習(xí)步調(diào)2:
MYSQL學(xué)習(xí)mysql> select count(1) from User where phone is null;
+----------+
| count(1) |
+----------+
| 70 |
+----------+
1 row in set (0.00 sec)
MYSQL學(xué)習(xí)經(jīng)2再次驗(yàn)證數(shù)據(jù)庫中null和空紛歧樣的兩個(gè)值.
MYSQL學(xué)習(xí)步調(diào)3:
MYSQL學(xué)習(xí)mysql> alter table User add constraint uk_phone unique(phone);
ERROR 1062 (23000): Duplicate entry '' for key 'uk_phone'
此時(shí)創(chuàng)建索引提示‘ '為一個(gè)重復(fù)的屬性.
MYSQL學(xué)習(xí)步調(diào)4:將所有的空值改成null
MYSQL學(xué)習(xí)mysql> update User set phone = NULL where phone = '';
Query OK, 40 rows affected (0.11 sec)
Rows matched: 40 Changed: 40 Warnings: 0
步調(diào)5:再次創(chuàng)建唯一索引
MYSQL學(xué)習(xí)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學(xué)習(xí)創(chuàng)建勝利,OK了
歡迎參與《MYSQL教程mysql 中存在null和空時(shí)創(chuàng)建唯一索引的方法》討論,分享您的想法,維易PHP學(xué)院為您提供專業(yè)教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/12294.html