Mysql with as定义子查询

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

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值