练习网站:https://sqlbolt.com/lesson/filtering_sorting_query_results
excel
法则
- col:属性
- SELECT col,col,col 属性
- FROM table 表
- WHERE col 条件
案例:
# 找出所有电影id和title
select ld from movies where 1;
select title from movies where 1;
条件查询
数字:
操作 | 解释 |
---|---|
=,!=,<,>,<=,>= | 等于,小于,大于 |
BETWEEN … AND … | 在X和X之间 |
NOT BETWEEN … AND … | 不在X和X之间 |
IN (…) | 在集合内 |
NOT IN (…) | 不在集合内 |
# 找出2010年的电影,只显示名字和年份
select title,year from movies where year=2010
# 找出id在3-6之间的
select title from movies where id between 3 and 6
select title from movies where id in (3,4,5,6)
select title from movies where id>=3 and id<=6
字符串:
操作 | 解释 |
---|---|
=,!=,like,not like | 等于,不等于 |
% | 通配符 |
- | 模糊匹配单字符 |
in(…), not in(…) | 在不在集合中 |
# 找出Toy Story系列的所有电影
select title from movies where title like "%Toy Story%"
对查询结果排序
按id排序,只取第2-6位
select * from movies where 1 order by Id desc limit 4 offset 2
操作 | 解释 |
---|---|
order by | 排序 |
asc | 升序 |
desc | 降序 |
limit | 显示结果数量 |
offset | 从第几个结果开始显示 |
多表关联
先连接表,再用单表操作
select *
from table1 left join table2 on table1.id=table2.movie_id
where 1
操作 | 解释 |
---|---|
join … on … | 连接两张表 |
left join | 以左边为主,保留t1所有row |
right join | 以右边为主,保留t2所有row |
inner join | 只保留公共部分,保留相等id的row |
is/is not null | col是不是为空 |
在查询中使用表达式
对查询结果做计算
操作 | 解释 |
---|---|
±*/% | 四则混合运算 |
substr | 字符串截取 substr(col,0,4) |
as | col取别名 |
select id,title,timelong/60 as timehour
from movies
where 1
统计
操作 | 解释 |
---|---|
count(col) | 统计 |
min(col) | 最小值 |
max(col) | 最大值 |
avg(col) | 平均 |
sum(col) | 求和 |
group by | 分组 |
having | 分组后条件 |
按年份分组统计电影总数
select year,count(Id) as total
from movies
where 1
group by year;