文章目录
- 1. 定义
- 2. 适用场景
- 3. 语法
- 4. 示例
1. 定义
使用with as 可以让子查询重用相同的with查询块,
并在select查询块中直接引用,
一般用在select查询块会多次使用某个查询sql时,
会把这个sql语句放在with as 中,
作为公用的表达式,通过别名的方式在主查询语句中重复使用。
2. 适用场景
因with as 子查询仅执行一次,将结果存储在用户临时表中,提高查询性能,
所以适合多次引用的场景,如:
复杂的报表统计,分页查询,且需要拿到sum、count、avg这类结果作为筛选条件,
对查询出的结果进行二次处理!特别对于union all比较有用。因为union all的每个部分可能相同,
但是如果每个部分都去执行一遍的话,则成本太高
3. 语法
使用语法:
WITH
(SELECT语句) AS 别名1,
(SELECT语句) AS 别名2,
...
SELECT * FROM 别名1,别名2 WHERE 别名1.id = 别名2.id;
4. 示例
sql1:
with student_tmp as (select * from xin_student_t where relation_id = 1)
select student_name from student_tmp where student_age = 12 union all select student_name from student_tmp where student_age = 13;
sql2:
with student_tmp as (select * from xin_student_t where relation_id in (1, 2, 3)),
teacher_tmp as (select * from xin_teacher_t where id in (1, 2, 3))
select subject from student_tmp where student_age = 12
union all select subject from teacher_tmp where teacher_age = 31
union all select student_tmp.subject from student_tmp, teacher_tmp where teacher_tmp.id = student_tmp.relation_id