MySQL LIKE子句
概述
LIKE运算符用于WHERE子句中的模式匹配。它在列中搜索指定的模式,支持通配符进行灵活匹配。
LIKE语法
sql
通配符
百分号
sql
-- Matches any sequence of characters
-- Matches zero or more characters下划线
sql
-- Matches exactly one character
-- Multiple underscores组合通配符
sql
-- Start with, end with
-- Complex patterns
-- Escape wildcardsLIKE模式
以...开头
sql
-- Names starting with A
-- Emails from specific domain
-- Products in category以...结尾
sql
-- Files with specific extension
-- Users with specific suffix包含
sql
-- Products containing 'pro'
-- Users with specific pattern
-- Case-insensitive contains指定模式
sql
-- Exactly 5 characters
-- Starts with A, ends with Z
-- Contains exactly 3 charactersNOT LIKE / NOT LIKE
sql
-- Does not start with
-- Does not contain
-- Does not match pattern不同数据类型的LIKE
字符串
sql
-- Text matching
-- Case sensitivity (MySQL LIKE is case-insensitive by default)数字
sql
-- Numbers as strings
-- ZIP codes日期
sql
-- Dates as strings
-- YearsESCAPE子句
转义默认字符
sql
-- Escape % character
-- Escape underscore自定义转义字符
sql
-- Use different escape character
-- Complex pattern with escape不同上下文中的LIKE
UPDATE语句
sql
-- Update matching patternsDELETE语句
sql
-- Delete matching patternsINSERT语句
sql
-- Not typically used in INSERT, but in SELECT for insert性能考虑
索引使用
sql
-- LIKE with leading wildcard cannot use index
-- LIKE without leading wildcard CAN use index
-- Leading wildcard pattern优化策略
sql
-- Avoid leading wildcards when possible
-- Instead of: WHERE email LIKE '%@gmail.com'
-- Use: WHERE email REGEXP '@gmail.com$' (still slow, but more flexible)
-- Use FULLTEXT search for large text columns
-- Consider('mysql tutorial storing reverse strings for trailing wildcardLIKE与其他模式匹配
LIKE与REGEXP比较
| 方面 | LIKE | REGEXP |
|---|---|---|
| 通配符 | %, _ | Complex regex |
| 性能 | Faster | Slower |
| 灵活性 | Limited | High |
| 开头通配符 | Cannot use index | Cannot use index |
| 用例 | Simple patterns | Complex patterns |
sql
-- LIKE examples
-- REGEXP examplesLIKE与IN比较
sql
-- IN for exact matches
-- LIKE for patterns实用示例
搜索功能
sql
-- Simple search
-- Search with word boundaries
-- Case-insensitive search数据验证
sql
-- Find invalid email patterns
-- Find invalid phone formats
-- Find malformed codes数据清洗
sql
-- Find duplicate-like entries
-- Find entries with special characters
-- Find empty or whitespace-only小结
LIKE子句提供:
通配符:%(任意),_(单个) 模式匹配:简单字符串模式 大小写敏感性:默认不区分大小写 ESCAPE:自定义转义字符 性能:避免开头通配符 替代方案:REGEXP用于复杂模式
上一个:DELETE
下一个:UNION