MySQL WHERE子句
概述
WHERE子句根据指定的条件过滤记录。它只提取满足指定条件的记录,使查询更精确、更高效。
WHERE语法
sql
比较运算符
基本比较
sql
-- Equal
-- Not equal
-- Greater than
-- Greater than or equal
-- Less than
-- Less than or equal范围运算符
sql
-- Between (inclusive)
-- Date range
-- NOT BETWEEN列表运算符
sql
-- In list
-- With subquery
-- NOT IN逻辑运算符
AND运算符
sql
-- Multiple conditions (all must be true)
-- Multiple AND conditions
-- Combine with other operatorsOR运算符
sql
-- Any condition true
-- Multiple OR conditionsAND与OR组合
sql
-- AND has higher precedence
-- Parentheses for clarityNOT运算符
sql
-- NOT equal
-- NOT IN
-- NOT BETWEEN
-- NOT LIKE
-- NOT NULL
-- Complex NOTNULL条件
IS NULL / IS NULL
sql
-- Find NULL values
-- Find missing relationships
-- Find incomplete recordsIS NOT NULL / IS NOT NULL
sql
-- Exclude NULL values
-- Only completed records模式匹配
LIKE / LIKE
sql
-- Starts with
-- Ends with
-- Contains
-- Single character wildcard
-- Multiple wildcardsNOT LIKE / NOT LIKE
sql
-- Does not start with
-- Does not contain大小写不敏感
sql
-- MySQL LIKE is case-insensitive by default
-- For case-sensitive comparison正则表达式
sql
-- Starts with
-- Ends with
-- Contains any of characters
-- Multiple options
-- Complex patterns
-- NOT REGEXP字符串比较
sql
-- Exact match
-- Case-insensitive comparison
-- Length comparison
-- String functions in WHERE
-- Concatenation comparison日期时间过滤
sql
-- Specific date
-- Date range
-- Time comparison
-- Year filter
-- Month filter
-- Day of week
-- Date functions数值过滤
sql
-- Aggregate functions in WHERE (using HAVING)
-- Subquery with aggregate
-- Mathematical operations组合条件
sql
-- Complex query
-- Using CASE in WHERE (advanced)性能考虑
索引使用
sql
-- Use indexed columns in WHERE
-- Function on column prevents index use
-- Rewrite to use index查询优化
sql
-- Put most selective condition first
-- Avoid SELECT *
-- Use LIMIT for testing故障排除
常见问题
sql
-- Unexpected results
-- Check: Operator precedence, parentheses
-- No results returned
-- Check: NULL comparisons (use IS NULL, not = NULL)
-- Case sensitivity
-- Check: String comparisons, collation settings
-- Date format
-- Check: Date format matches MySQL expectations (YYYY-MM-DD)调试
sql
-- Add EXPLAIN to see query plan
-- Test conditions separately
-- Check data types小结
WHERE子句过滤包括:
比较运算符 范围运算符 逻辑运算符 NULL处理 模式匹配 Time**: Date functions / 日期时间 性能优化
上一个:查询数据
下一个:UPDATE