请教左联结中的过滤条件

leon51 2020-07-02 10:57:13
有一个SQL语句,需使用left join联结多个表。
我想先对左表作一些过滤这样效率应该会高一点。
之前我是使用with语句先将左表筛选出来然后再用left join联结,但这样有个弊端,就是那些结果的字段要重复的写一遍

举个例子,下面的语句中我需要先从job表中找出customer中包含字符“ABC”,
我将Where a.customer like '%ABC%'放在on的后面,但是查资料说where在最后才执行的,这样并不会提高效率,请问应该怎么修改才能首先对左表过滤?

select 
a.job_name,
a.customer,
b.job_desc
from job a
left join description b
on a.job_name = b.job_name


...全文
101 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
leon51 2020-07-02
  • 打赏
  • 举报
回复
引用 1 楼 wildwolv 的回复:
select a.job_name, a.customer, b.job_desc from (select * from job Where customer like '%ABC%' )a left join description b on a.job_name = b.job_name
非常感谢你的回复,追问下,如果要对右表使用group by子句怎么写呢?
wildwolv 2020-07-02
  • 打赏
  • 举报
回复
select a.job_name, a.customer, b.job_desc from (select * from job Where customer like '%ABC%' )a left join description b on a.job_name = b.job_name
lhdz_bj 2020-07-02
  • 打赏
  • 举报
回复
1、
select
a.job_name,
a.customer,
b.job_desc
from (select * from job Where customer like '%ABC%' )a
left join description b
on a.job_name = b.job_name;
这种写法可以,但有时内联视图也会被展开,所以,未必就能保证条件like '%ABC%'会被先执行。最好加个hint阻止展开:
select /*+ no_merge(a) */
a.job_name,
a.customer,
b.job_desc
from (select * from job Where customer like '%ABC%' )a
left join description b
on a.job_name = b.job_name;
2、如果要对右表使用group by子句怎么写呢?
直接用右表字段分组,例如:
select /*+ no_merge(a) */
b.job_desc,count(1)
from (select * from job Where customer like '%ABC%' )a
left join description b
on a.job_name = b.job_name
group by b.job_desc;
卖水果的net 2020-07-02
  • 打赏
  • 举报
回复
但是查资料说where在最后才执行的,这样并不会提高效率 看实际的执行计划,资料只是参考。

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧