Skip to content

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 operators

OR运算符

sql
-- Any condition true

-- Multiple OR conditions

AND与OR组合

sql
-- AND has higher precedence

-- Parentheses for clarity

NOT运算符

sql
-- NOT equal

-- NOT IN

-- NOT BETWEEN

-- NOT LIKE

-- NOT NULL

-- Complex NOT

NULL条件

IS NULL / IS NULL

sql
-- Find NULL values

-- Find missing relationships

-- Find incomplete records

IS NOT NULL / IS NOT NULL

sql
-- Exclude NULL values

-- Only completed records

模式匹配

LIKE / LIKE

sql
-- Starts with

-- Ends with

-- Contains

-- Single character wildcard

-- Multiple wildcards

NOT 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