Oracle with as用法

发布于:2024-03-15 ⋅ 阅读:(113) ⋅ 点赞:(0)

一、简介

with…as关键字,是以‘with’关键字开头的sql语句,在实际工作中,我们经常会遇到同一个查询sql会同时查询多个相同的结果集,即sql一模一样,这时候我们可以将这些相同的sql抽取出来,使用with…as定义。with…as相当于一张中间表,可以简单理解为sql片段(类似java复用代码)。

下面我们通过两个简单的示例说明with…as的使用方法。

二、使用方法

【a】多次使用抽取出来

–with as 可以理解为一张临时表或者理解成sql片段,在多次查询语句相同的时候可以抽取出来,达到’一次解析,多次使用’
–如果每个部分都去执行一遍的话,则成本比较高,可以使用with as短语,则只要执行一遍即可

with temp as
 (select '10001' as province_code from dual)
 
select case
         when (select * from temp) = '10001' then
          'equals'
         when (select * from temp) = '10002' then
          'not equals'
         else
          'unknown'
       end is_equals
  from dual;

img

【b】在union 语句中使用

--with as 非常适合在union 语句中
--注意:with as 语句最后面不能加分号,否则报缺失select关键字错误。
with temp1 as
 (select 'female' sex, 'zhangsan' stu_name from dual),
temp2 as
 (select 'male' sex, 'lisi' stu_name from dual),
temp3 as
 (select 'female' sex, 'wangwu' stu_name from dual)
 
select *
  from temp1
union all
select *
  from temp2
union all
select * from temp3

在这里插入图片描述

在这里插入图片描述

注意点:with…as后面不能加分号,否则报错。

【c】注意点:

  1. 不能只定义with…as语句,定义了要使用它,否则会报错
--只定义with..as会报错
with temp1 as
 (select 'female' sex, 'zhangsan' stu_name from dual),
temp2 as
 (select 'male' sex, 'lisi' stu_name from dual)

在这里插入图片描述

  1. 前面定义的with…as语句可以在后面定义的with…as语句中使用
--前面定义的with..as语句可以在后面定义的with..as语句使用
with temp1 as
 (select 'female' sex, 'zhangsan' stu_name from dual),
temp2 as
 (select 'male' sex, 'lisi' stu_name from dual),
temp3 as
 (select * from temp2)
 
select *
  from temp1
union all
select *
  from temp2
union all
select * from temp3

在这里插入图片描述

三、总结

with…as其实就是将经常需要查询的语句抽取出来,形成一个虚拟表,我们后面可以多次使用,达到‘一次解析,多次使用’的效果,大大提高执行的效率。

本文含有隐藏内容,请 开通VIP 后查看

网站公告


今日签到

点亮在社区的每一天
去签到