with as:也叫子查询,先通过with语法将数据查询到内存,后面其它查询可以直接使用,不仅提高了查询性能,同时也提高了代码的可读性
##单个as情况,相当于套了一个子查询在里边
with t1 as (
select * from test
)
select * from t1;
##效果等同于
select * from
(
select * from test
)t1; t2
##多个as情况
with t1 as (
select b.id,b.name,c.score --id,姓名,成绩
from student b
left join class c
on b.id=c.id
)
,t2 as (
select * from test
)
select * form t1,t2 where t1.id=t2.id;
注意事项:
1.前面每个as里都相当于一个子查询,可以看作一个独立模块,最后select则是整体查询,也是最终展示的查询结果
2.with 子句必须在select之前定义
3.多个子句之间使用逗号分隔即可,最后一个子句与后面的查询语句不需要在添加逗号