Home > Database > Mysql Tutorial > body text

mysql 中存在null和空时创建唯一索引的方法

WBOY
Release: 2016-06-07 16:27:56
Original
1100 people have browsed it

好多情况下数据库默认值都有null,但是经过程序处理很多时候会出现,数据库值为空而不是null的情况。此时创建唯一索引时要注意了,此时数据库会把空作为多个重复值,而创建索引失败,示例如下: 步骤1: mysql select phone ,count(1) from User group by ph

好多情况下数据库默认值都有null,但是经过程序处理很多时候会出现,数据库值为空而不是null的情况。此时创建唯一索引时要注意了,此时数据库会把空作为多个重复值,而创建索引失败,示例如下:

步骤1:

mysql> select phone ,count(1) from User group by phone;
+-----------------+----------+
| phone | count(1) |
+-----------------+----------+
| NULL | 70 |
| | 40 |
| +86-13390889711 | 1 |
| +86-13405053385 | 1 |

步骤一中发现数据库中有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'
此时创建索引提示‘ '为一个重复的属性。

步骤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:再次创建唯一索引

mysql> alter table User add constraint uk_phone unique(phone);
Query OK, 0 rows affected (0.34 sec)
Records: 0 Duplicates: 0 Warnings: 0

创建成功,OK了

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template