MYSQL公共表达式的应用


一、mysql公共表达式

mysql的公共表达式跟select字句一样,不同的是公共表达式需要定义并且可以重复使用,而select字句一般都是现用现写,第二次想用则需要再次去写。公共表达式可以理解为对select字句的定义

二、使用实例

1.引入

代码如下(示例):

with cte as (select title, class_id
from imc_course where study_cnt > 200)
select * from cte
union all
select * from cte
order by title;

执行结果如下
在这里插入图片描述

2.生成序列

with recursive test as (
    select 1 as n
    union all
    select 1+n from test where n<10
)
select * from test;

执行结果如下
在这里插入图片描述

3.递归查询回复信息

with recursive reply(quest_id, quest_title, user_id, replyid, path) as (
    select quest_id, quest_title, user_id, replyid, cast(quest_id as char(200)) as path
    from imc_question where course_id = 59 and replyid = 0
    union all
    select a.quest_id, a.quest_title, a.user_id, a.replyid, concat(b.path, '>>', a.quest_id) as path
    from imc_question a
    join reply b on a.replyid = b.quest_id
)
select * from reply;

执行结果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值