MySQL NULL值处理
概述
NULL表示MySQL中缺失或未知的数据。了解如何处理NULL值对于编写正确的查询和维护数据完整性至关重要。
理解NULL
无值或未知值 NULL不同于0 NULL不同于空字符串'' NULL比较需要特殊运算符
NULL与空值的区别
对比表
| 值 | IS NULL / IS NULL | IS NOT NULL / IS NOT NULL | = '' / = '' | = 0 / = 0 |
|---|---|---|---|---|
| NULL | TRUE | FALSE | NULL | NULL |
| '' (empty string) | FALSE | TRUE | TRUE | FALSE |
| 0 | FALSE | TRUE | FALSE | TRUE |
示例
sql
-- Check NULL values测试NULL
IS NULL和IS NOT NULL
sql
-- Find rows with NULL values
-- Find rows without NULL values
-- Multiple NULL checksCOALESCE函数
sql
-- Return first non-NULL value
-- Nested COALESCEIFNULL函数
sql
-- Return second value if first is NULL
-- In calculationsNULL在比较中
NULL比较行为
sql
-- These comparisons return NULL, not TRUE or FALSE
-- Use IS NULL insteadNULL在WHERE子句中
sql
-- Correct: Use IS NULL
-- Incorrect: Will not work as expected
-- Multiple NULL conditions
-- Using OR with NULLNULL在表达式中
算术运算
sql
-- Any operation with NULL returns NULL
-- If discount is NULL, total is NULL
-- Use IFNULL or COALESCE to handle字符串运算
sql
-- Concatenation with NULL
-- If middle_name is NULL, full_with_middle is NULL
-- Use CONCAT_WS (skip NULL)
-- CONCAT_WS skips NULL valuesNULLIF函数
sql
-- Return NULL if two expressions are equal
-- Returns NULL if price equals discount_price
-- Use in calculationsNULL在聚合中
COUNT和NULL
sql
-- COUNT(*) includes NULL
-- COUNT(column) excludes NULLSUM、AVG和NULL
sql
-- Aggregate functions ignore NULL
-- SUM and AVG only include non-NULL values
-- With NULL handlingGROUP BY和NULL
sql
-- NULL values are grouped together
-- All NULL departments are in one group
-- Handle NULL in groupingNULL在ORDER BY中
sql
-- NULL values in sorting
-- Control NULL placement (MySQL 8.0+)
-- Custom NULL ordering (older versions)NULL在唯一约束中
UNIQUE和NULL行为
sql
-- Multiple NULL values allowed in UNIQUE column
-- These are allowed
-- Multiple NULL emails are allowed
-- But duplicate non-NULL values are not
-- Error: Duplicate entryNULL在外键约束中
sql
-- NULL allowed in foreign key
-- Orders without customer (NULL customer_id allowed)
-- Find orders without customer
-- Find orders with customerNULL处理函数
ISNULL函数
sql
-- Test if expression is NULLNVL函数(Oracle兼容)
sql
-- NVL equivalent to IFNULLLEAST和GREATEST与NULL
sql
-- LEAST and GREATEST return NULL if any argument is NULL
-- Use COALESCE to handle NULLNULL在视图中
sql
-- Views can contain NULL values
-- Query viewNULL在存储过程中
sql
-- Set default if NULL
-- Call procedureNULL最佳实践
设计建议
sql
-- Use NULL for optional data
-- Use DEFAULT values instead of NULL when appropriate查询性能
sql
-- Index columns with NULL
-- NULL values can affect index usage
-- Use IS NOT NULL for indexed columns数据完整性
sql
-- Use NOT NULL for required fields小结
正确处理NULL值对于以下方面至关重要:
数据准确性:NULL表示缺失数据 查询正确性:使用IS NULL而不是= NULL 数据完整性:必需字段的NOT NULL约束 显示:COALESCE和IFNULL实现用户友好的输出 计算:处理算术运算中的NULL
上一个:连接
下一个:正则表达式