数据库学习笔记(5)-----with as的用法(2019/2/28)
有如下表’student’
name | lesson | grade |
---|---|---|
Joson | Math | 95 |
Joson | Chinese | 25 |
Joson | English | 80 |
Joson | Biology | 75 |
Joson | Phycial | 55 |
此时,我们可以通过with as方式,将这张表拆分为N张表存进当前SQL窗口的缓存中,例如:
with stu_name as(
select name,lesson from student;
),stu_grade as(
select name,lesson,grade from student;
)
那么,将会有两张临时表被存入了缓存中,分别叫做’stu_name’和’stu_grade’
stu_name:
name | lesson |
---|---|
Joson | Math |
Joson | Chinese |
Joson | English |
Joson | Biology |
Joson | Phycial |
stu_grade:
name | lesson | grade |
---|---|---|
Joson | Math | 95 |
Joson | Chinese | 25 |
Joson | English | 80 |
Joson | Biology | 75 |
Joson | Phycial | 55 |
如果我们想对这两张表进行操作的时候,可以使用如下方法:
with stu_name as(
select name,lesson from student;
),stu_grade as(
select name,lesson,grade from student;
)select * from stu_name;
记住:with as后面只能跟子查询语句,也就是’select’语句。
那么,如果我们需要将这份信息进行插入的时候,应该怎么办呢?可以用如下方法:
insert into dual(dummy)
with stu_name as(
select name,lesson from student;
),stu_grade as(
select name,lesson,grade from student;
)select name from stu_name;
此时就可以将’name’字段的数据插入’dual’表中了。
另:
用with as的优点:
1、在需要多个子查询的情况下,逻辑结构层次清晰,便于维护。
2、真正的做到了’一次读取,终生受用’对于需要重复读取表格数据的子查询语句的性能优化有很大的用处。
敲黑板:
在使用with as的时候,命名尽可能规范,注释尽可能完善,不然,其他小伙伴读你的代码的时候,比读子查询更累哦(Φ皿Φ)。