基础查询
以极客时间专栏《SQL必知必会》的王者荣耀表格为例。
SELECT
语句
检索单个列
查询语句:
SELECT name
FROM heros
结果:
检索多个列
查询语句:
SELECT name, hp_max
FROM heros
检索多个列
查询语句:
image.png检索所有列
查询语句:
SELECT *
FROM heros
注:生产条件下,不推荐查询所有列名,最好列出所需列名,减轻数据库的负荷,提升性能。
检索不同的行
去重
查询语句:
SELECT DISTINCT role_main
FROM heros
限制结果
查询语句:
SELECT NAME,hp_max FROM heros LIMIT 5
查询语句:
SELECT NAME,hp_max FROM heros
LIMIT 5,6
查询排序
ORDER
语句
按照一列排序
查询语句:
SELECT NAME,hp_max,hp_growth FROM heros
ORDER BY hp_growth
LIMIT 5
结果:
按照多列排序
查询语句:
SELECT NAME,hp_max,hp_growth,hp_start FROM heros
ORDER BY hp_start,hp_max
LIMIT 5
指定排序方向
查询语句:
SELECT NAME,hp_max,hp_growth,hp_start FROM heros
ORDER BY hp_max DESC
LIMIT 5
结果:
查询语句:
SELECT name ,hp_max,hp_growth,hp_start FROM heros
ORDER BY hp_max DESC, hp_growth
LIMIT 5
结果:
查询过滤
WHERE
语句
操作符 | 说明 |
---|---|
= | 等于 |
< | 小于 |
> | 大于 |
<> != | 不等于 |
<= !> | 小于等于 |
>= !< | 大于等于 |
BETWEEN | 在两个值之间 |
IS NULL | 为 NULL 值 |
检查单个值
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start
FROM heros
WHERE hp_max > 8000
ORDER BY hp_max DESC
LIMIT 5
结果:
匹配检查
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start
FROM heros
WHERE role_main = '战士'
ORDER BY hp_max DESC
LIMIT 5
结果:
不匹配检查
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start
FROM heros
WHERE role_main <> '坦克'
ORDER BY hp_max DESC
LIMIT 5
结果:
范围值检查
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start
FROM heros
WHERE hp_max BETWEEN 7500 AND 8000
ORDER BY hp_max DESC
结果:
空值检查
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start,role_assist
FROM heros
WHERE role_assist IS NULL
ORDER BY hp_max DESC
LIMIT 5
结果:
组合WHERE
子句
AND 操作符
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start,role_assist
FROM heros
WHERE role_assist IS NULL AND hp_growth >380
ORDER BY hp_max DESC
OR操作符
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start,role_assist
FROM heros
WHERE role_main = '射手' OR role_main = '法师'
ORDER BY hp_max DESC
LIMIT 10
结果:
IN操作符
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start,role_assist
FROM heros
WHERE role_main IN ('射手','法师','刺客')
ORDER BY hp_max DESC
LIMIT 10
结果:
NOT操作符
查询语句:
SELECT name ,role_main, hp_max,hp_growth,hp_start,role_assist
FROM heros
WHERE role_main NOT IN ('射手','法师','刺客')
ORDER BY hp_max DESC
LIMIT 10
结果:
计算次序
SELECT的执行顺序:
SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ...
优先级:
FROM > WHERE > GROUP BY > HAVING > SELECT 的字段 > DISTINCT > ORDER BY > LIMIT
示例:
SELECT DISTINCT player_id, player_name, count(*) as num # 顺序 5
FROM player JOIN team ON player.team_id = team.team_id # 顺序 1
WHERE height > 1.80 # 顺序 2
GROUP BY player.team_id # 顺序 3
HAVING num > 2 # 顺序 4
ORDER BY num DESC # 顺序 6
LIMIT 2 # 顺序 7
Ref:
- 《MySQL必知必会》(Ben Forts)
- 极客时间《SQL必知必会》
网友评论