MySQL中NULL的处理和特性
NULL Value
NULL 表示不存在的未知的值
NULLmeans "a missing unknown value" or "not having a value"
操作NULL
使用 is null 和 is not null 操作符及ifnull 函数
特性
-
对
NULL使用算术运算符,例如=<><>,都会返回NULL(无意义的结果)mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL; +----------+-----------+----------+----------+ | 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL | +----------+-----------+----------+----------+ | NULL | NULL | NULL | NULL | +----------+-----------+----------+----------+ -
任何包含
NULL的表达式都会返回NULL,除非文档中针对表达式中涉及的运算符和函数另有说明An expression that contains
NULLalways produces aNULLvalue unless otherwise indicated in the documentation for the operators and functions involved in the expressionmysql> SELECT NULL, 1+NULL, CONCAT('Invisible',NULL); +------+--------+--------------------------+ | NULL | 1+NULL | CONCAT('Invisible',NULL) | +------+--------+--------------------------+ | NULL | NULL | NULL | +------+--------+--------------------------+ -
在MySQL 中,
0和NULL被视为false,其他值被视为true(布尔操作符返回1) -
InnoDB引擎支持在包含
NULL的列上建立索引 -
在
group byorder bydistinct中,两个NULL是相等的 -
在
order by中,升序排序时,NULL排在第一位;降序排序时,NULL排在最后 -
在
where中,算术运算符对NULL而言,返回的都是NULL,而NULL被视为false,因此不满足条件,不会返回 -
具有
NOT NULL约束的列,可以插入0和""mysql> SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL; +-----------+---------------+------------+----------------+ | 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL | +-----------+---------------+------------+----------------+ | 0 | 1 | 0 | 1 | +-----------+---------------+------------+----------------+ -
聚合函数
COUNT()MIN()SUM会忽略NULL特别的
COUNT(*),计算的是行数,而非列值 -
字段类型是
TIMESTAMP的列,插入NULL会插入当前日期和时间5.7版本,实际测试插入的还是NULL
占用空间
针对 InnoDB引擎
-
An SQL
NULLvalue reserves one or two bytes in the record directory. An SQLNULLvalue reserves zero bytes in the data part of the record if stored in a variable-length column. For a fixed-length column, the fixed length of the column is reserved in the data part of the record. Reserving fixed space forNULLvalues permits columns to be updated in place fromNULLto non-NULLvalues without causing index page fragmentation.https://dev.mysql.com/doc/refman/8.0/en/innodb-row-format.html
-
A
LENGTHofNULLisNULL, aLENGTHof an empty string is0.
NULL和空字符串的区别
插入
mysql> INSERT INTO my_table (phone) VALUES (NULL); -- 插入 NULL
mysql> INSERT INTO my_table (phone) VALUES (''); -- 插入 "" (空字符串)
- 插入 NULL 值,表示手机号是「未知状态」(不知道有没有手机号)
- 插入空字符串,表示「没有手机号」
查询
mysql> SELECT * FROM my_table WHERE phone IS NULL;
mysql> SELECT * FROM my_table WHERE phone = '';
参考
https://dev.mysql.com/doc/refman/8.0/en/working-with-null.html
https://dev.mysql.com/doc/refman/8.0/en/problems-with-null.html

浙公网安备 33010602011771号