MySQL中唯一性約束下能否有空值,空字符串


*問題 1*

首先,需要搞清楚 “空字符串” 和”NULL”的概念: 
1:空字符串(”)是不占用空間的 
2: MySQL中的NULL其實是占用空間的。官方文檔說明:

NULL columns require additional space in the row to record whether their values are NULL. For MyISAM tables, each NULL column takes one bit extra, rounded up to the nearest byte.

長度驗證:注意空值的”之間是沒有空格的。

select length(''),length(null),length(' ');
+------------+--------------+-------------+
| length('') | length(null) | length(' ') |
+------------+--------------+-------------+
|          0 |         NULL |           1 |
+------------+--------------+-------------+

 

准備數據:

create table abc(
    -> id int(10) primary key,
    -> c varchar(10) unique default '');  # 主要是為了測試唯一性約束下是否能存在重復的 Null,還有空字符串

 insert into abc value(1,Null);

insert into abc value(2,'');

 insert into abc value(3,'Null');

 

問題2:查詢非空字段的兩種方法的區別:

 1、select * from tablename where columnname <> ‘’

select * from abc where c <> '';   # 確實存在的字符串或者數據
+----+------+
| id | c    |
+----+------+
|  3 | Null |
+----+------+

 

2、select * from tablename where column is not null

 select * from abc where c is not null;
+----+------+
| id | c    |
+----+------+
|  2 |      |
|  3 | Null |
+----+------+

 

插入二次數據

mysql> insert into abc value(4,'');
ERROR 1062 (23000): Duplicate entry '' for key 'c'
# 說明 有唯一性約束的情況下不能有重復的空字符串

 mysql> insert into abc value(5,Null);
 Query OK, 1 row affected (0.05 sec)

 # 可以有重復的空值Null

**主鍵和唯一鍵約束是通過參考索引實施的,如果插入的值均為NULL,則根據索引的原理,全NULL值不被記錄在索引上,所以插入全NULL值時,可以有重復的,而其他的則不能插入重復值

 

## 小結:
1、NULL其實並不是空值,而是要占用空間,所以MySQL在進行比較的時候,NULL會參與字段比較,所以對效率有一部分影響。 而且對表索引時不會存儲NULL值的,所以如果索引的字段可以為NULL,索引的效率會下降很多

2、空值不一定為空
對於MySQL特殊的注意事項,對於timestamp數據類型,如果往這個數據類型插入的列插入NULL值,則出現的值是當前系統時間。插入空值,則會出現 ‘0000-00-00 00:00:00’ 

 

參考:https://blog.csdn.net/yu757371316/article/details/53033118


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM