模糊查询 LIKE 与通配符
57.11 模糊查询 LIKE 与通配符
LIKE 模式匹配;NOT LIKE 取不匹配的行。
% 代表任意长度字符串(含零个字符);_ 代表恰好一个字符。
查「姓小」:LIKE '小%';查「两字名且第二字为明」:LIKE '_明'。
- %a% — 含 a
- a% — 以 a 开头
- %a — 以 a 结尾
- _at — 三字母且后两位 at
通配符示例
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='py_demo', charset='utf8mb4')
try:
with conn.cursor() as cur:
cur.execute("SELECT name FROM students WHERE name LIKE '小%'")
print('姓小:', cur.fetchall())
cur.execute("SELECT name FROM students WHERE name LIKE '_红'")
print('某字+红:', cur.fetchall())
cur.execute('SELECT name FROM students WHERE email LIKE %s', ('%@test.com',))
print('test.com 邮箱:', cur.fetchall())
finally:
conn.close()