Skip to content

MySQL NULL值处理

概述

NULL表示MySQL中缺失或未知的数据。了解如何处理NULL值对于编写正确的查询和维护数据完整性至关重要。

理解NULL

无值或未知值 NULL不同于0 NULL不同于空字符串'' NULL比较需要特殊运算符

NULL与空值的区别

对比表

IS NULL / IS NULLIS NOT NULL / IS NOT NULL= '' / = ''= 0 / = 0
NULLTRUEFALSENULLNULL
'' (empty string)FALSETRUETRUEFALSE
0FALSETRUEFALSETRUE

示例

sql

-- Check NULL values

测试NULL

IS NULL和IS NOT NULL

sql
-- Find rows with NULL values

-- Find rows without NULL values

-- Multiple NULL checks

COALESCE函数

sql
-- Return first non-NULL value

-- Nested COALESCE

IFNULL函数

sql
-- Return second value if first is NULL

-- In calculations

NULL在比较中

NULL比较行为

sql
-- These comparisons return NULL, not TRUE or FALSE

-- Use IS NULL instead

NULL在WHERE子句中

sql
-- Correct: Use IS NULL

-- Incorrect: Will not work as expected

-- Multiple NULL conditions

-- Using OR with NULL

NULL在表达式中

算术运算

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 values

NULLIF函数

sql
-- Return NULL if two expressions are equal
-- Returns NULL if price equals discount_price

-- Use in calculations

NULL在聚合中

COUNT和NULL

sql
-- COUNT(*) includes NULL
-- COUNT(column) excludes NULL

SUM、AVG和NULL

sql
-- Aggregate functions ignore NULL
-- SUM and AVG only include non-NULL values

-- With NULL handling

GROUP BY和NULL

sql
-- NULL values are grouped together
-- All NULL departments are in one group

-- Handle NULL in grouping

NULL在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 entry

NULL在外键约束中

sql
-- NULL allowed in foreign key

-- Orders without customer (NULL customer_id allowed)

-- Find orders without customer

-- Find orders with customer

NULL处理函数

ISNULL函数

sql
-- Test if expression is NULL

NVL函数(Oracle兼容)

sql
-- NVL equivalent to IFNULL

LEAST和GREATEST与NULL

sql
-- LEAST and GREATEST return NULL if any argument is NULL

-- Use COALESCE to handle NULL

NULL在视图中

sql
-- Views can contain NULL values

-- Query view

NULL在存储过程中

sql
    
    -- Set default if NULL
    

-- Call procedure

NULL最佳实践

设计建议

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


上一个:连接

下一个:正则表达式