复杂查询
视图
- 视图存放sql查询语句,而非数据
- 为什么使用
- 提高效率
- 数据会自动更新
- 不用保存,可以节省存放数据设备的空间
- 事项
- 避免多重视图
- 不能往视图里面插入数据,以免报错
create view summary(sex, person) as
select s_sex, count(*)
from student
group by s_sex;
子查询
- 在一个select查询语句中嵌套了另一个select查询语句
- 临时表
-- 查询每个课程里成绩最低的学号
select s_id, s_score from score
where s_score in
(
select min(s_score) from score
group by c_id
)
any all 子查询
-- 哪些学生的成绩比课程0002的全部课程里的任意一个高呢?
-- 哪些学生的成绩比课程0002的全部成绩里的都高呢?
- 偶尔使用:子查询
- 频繁使用:私家车
注意事项: - 避免使用层层嵌套 - 书写规范,养成良好习惯
标量子查询
- where子句中不能使用汇总函数
- 返回单一的值(一行一列)
-- 查找成绩介于差生平均成绩和优等生平均成绩之间的学生有哪些
任何使用单一值的地方,都可以使用标量子查询
关联子查询
-- 查询每个课程中大于对应课程平均成绩的学生
select a.s_id, a.c_id, a.s_score from score as a
where s_score > (select avg(s_score) from score as b
where a.c_id=b.c_id
group by c_id);
用SQL解决业务问题
- 翻译成大白话
- 写出分析思路
- 写出对应的SQL语句
- 报错,排除法逐一排查
各种函数
- round(123.234, 2)
- abs(-100)
- mod(5,2)
- length('abcde')
- lower('A')
- upper('a')
- concat('A', 'B')
- replace('acb', 'b', 'd')
- substring('abcde', 2, 3)
- current_date
- current_time
- current_timestamp
- year('2020-05-02')
- month('2020-05-02')
- day('2020-05-02')
- dayname('2020-05-02 10:41:23')