3赞
447
当前位置:  开发笔记 > 编程语言 > 正文

sql中简简单单明明白白得使用withtempas(selectxfromtable1)

原创地址:https:blog.csdn.netQQ826688096articledetails89379997今天在看博客得时候,发现了一个我不曾使

原创地址:https://blog.csdn.net/QQ826688096/article/details/89379997
今天在看博客得时候,发现了一个我不曾使用过得sql语法,感到很奇怪,就多看了几下。
发现还是很有用处得。
于是从地铁里出来后收起手机,直奔公司,打开电脑,使用了一下。
我去,上来就报错。
在这里插入图片描述

with temp_xs as (select xydm from xj_xsxxb where xh like'%001510%'),temp_js as (select xydm from sz_jsxxb where zgh like'%001510%')
select t.* from dm_yxb t
where t.yxdm =temp_xs.xydm or t.yxdm =temp_js.xydm;

这么看上面得代码也没有什么问题啊。
我记得我看清楚人家语法了啊,差不多就是这么写的啊,难道是我的表里有什么东西?


于是流程式的检验一下:
1,检验基本语法;
2,去除无用字段;
3,将变量值改成常量值。


最后发现,都没有问题!!!
于是我再去好好看看人家的成功案例,经过逐字逐句的检查,发现了端倪。
一个不容易被发现的端倪:
with 子句获得的是一个【临时表,如果在查询中使用,必须采用select 字段名 from with得表名】】,
比如,下面这样得写法就是错误的:

With temp_count as(select count(*) as countt from table)
Select temp_count+1 from dual;

下面才是正确的:

With temp_count as(select count(*) countt from user_tables)
Select (countt+1) from temp_count;

于是,我终于找到原因了。修改后,可以执行了:

with temp_xs as (select xydm from xj_xsxxb where xh like'%001510%'),temp_js as (select xydm from sz_jsxxb where zgh like'%001510%')
select t.* from dm_yxb t
where t.yxdm in(select xydm from temp_xs union select xydm from temp_js);

不过,我做了个对比,这种写法和 left join得写法得执行效率是一样得。没有得到提升,也没有拖后。下面就是传统的left join得写法,执行效率和with得一样的。

select t.* from dm_yxb t
left join (select xydm from xj_xsxxb where xh like'%001510%') temp_xs on temp_xs.xydm=t.yxdm
left join (select xydm from sz_jsxxb where zgh like'%001510%') temp_js on temp_js.xydm=t.yxdm
where t.yxdm in(temp_xs.xydm) or t.yxdm in(temp_js.xydm);

语法讲解:

在这里插入图片描述
于是,我就去百度一下with temp as 得好处:


  1. SQL可读性增强。比如对于特定with子查询取个有意义的名字等。
  2. with子查询只执行一次,将结果存储在用户临时表空间中,可以引用多次,增强性能。

重要参考:https://blog.csdn.net/rosanu_blog/article/details/8288548


推荐阅读
author-avatar
chenyanni1030_430
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有