第十九天,SQL的一些高级用法
18周 JAVA从入门到入土
一、高级查询
1.1 建表
drop table if exists tb;
creat table tb
(
id int primary key auto_increment,
col1 varchar(10),
col2 date,
…
)
1.2 分组查询
select col1,聚合函数(col2) 别名
from tb
where …
group by col1
having …;
1° 聚合函数又叫做组函数:
- max() 取最大
- min() 取最小
- avg() 取平均
- sum() 求和
- count() 计数
2° where 和 having
两者都用于过滤,where用于分组前,having用于分组后。
1.3 子查询
select from tb where col in ();
select from tb where exists ();
两者括号内都可以放入一个子查询。
in 操作先处理子查询,子查询返回一个结果集,然后在主查询里筛选出最终结果。
exists 操作先处理主查询,再针对每一条结果用子查询来判断,最终结果显示所有子查询返回为真的条目。
所以,主查询范围小的建议用 exists,子查询范围小的建议用 in。
1.4 联表查询
1° 联表格式
select col1,col2,col3…
from tb1
inner join tb2
on tb1.col=tb2.col;
2° 联表种类
- 内联 inner join 只会包含所有两表能匹配到的条目
- 左联 left join 会保证包含左表的全部数据
- 右联 right join 会保证包含右表的全部数据
- 全外联 full out join 结果拥有两个表的全部数据
MySQL中没有全外联的语法
1.5 联合查询
1° 联合格式
select *
from tb1
union
select *
from tb2;
联合是将两个表合并为一个表。
2° union 与 union all
union 会去除重复部分,
union all 会保留全部数据
3° 联合查询实现全外联
将两表的左联结果与右联结果进行联合查询操作。
1.6 排序
select *
from tb
order by col asc/desc
1.7 case-when-then-end 语句
select col1,col2,col3,…,
case
when col<=val1 then ‘A’
when col>val1 and col<=val2 then ‘B’
when col>val2 and col<=val3 then ‘C’
…
end
from tb;
常用于对一个字段进行评级操作。
1.8 表的复制
insert into tb2
select * from tb1;
1.9 表的清空
delete from tb;
truncate tb;
delete 只是数据上的删除,不重置主键;
truncate 是整表清除,同时会重置主键。