sql - 有没有办法在不写两次左连接子查询的情况下逃脱?
问题描述
我的 SQL 没有想象中的那么强大。与编写 C# 相比,这是一种不同的思维方式。我正在处理一个查询并使用“left join/is null”重写它,以摆脱“not in”语法。
select t1.id, t2.col1
from table1 t1
join table2 t2 on t1.id = t2.id
left join (select sub.id from ratherLargeSubquery sub) s1
On s1.id = t1.id
left join (select sub.id from ratherLargeSubquery sub) s2
On s2.id = t2.id
where
s1.id is null and
s2.id is null
有什么办法可以避免两次编写相当大的子查询吗?我试过了
select t1.id, t2.col1
from table1 t1
join table2 t2 on t1.id = t2.id
left join (select sub.id from ratherLargeSubquery sub) s1
On (s1.id = t1.id and t2.id = s1.id)
where
s1.id is null
但当然,这会返回相同的结果,就好像我从来没有添加过左连接一样
select t1.id, t2.col1
from table1 t1
join table2 t2 on t1.id = t2.id
left join (select sub.id from ratherLargeSubquery sub) s1
On (s1.id = t1.id or s1.id = t2.id)
where
s1.id is null
只运行原始查询的 20 倍以上的时间,而每次都没有返回任何结果。
回到问题,有没有什么方法可以不用写两次相当大的子查询
解决方案
因为您没有从子查询中选择任何列,所以您可以将过滤移至where
子句。
select t1.id, t2.col1
from table1 t1 join
table2 t2
on t1.id = t2.id
where not exists (select 1
from ratherLargeSubquery sub
where sub.id = t1.id or sub.id = t2.id
);
这简化了查询的编写。但是,Oracle 可能无法对其进行优化。
推荐阅读
- mysql - R:Windows 上的 MySQL 字符编码
- python-2.7 - 如何修复新的 chrome 驱动程序的异常 - WebDriverException:消息:无效参数:值必须是非负整数
- haskell - 如何在 Haskell 源文件中包含多行编号?
- javascript - 用一个表连接 3 个表
- git - 致命:无法读取“https://OrganizationName@dev.azure.com”的密码:终端提示已禁用
- android - Kotlin: unresolved reference for Updating UI using Observables
- google-apps-script - 用静态值替换公式
- java - 定时器启动后可切换按钮不起作用
- group-by - Salesforce SOQL GROUP BY 是否区分不同区域设置的大小写?
- java - Does Jackson deserialization have a maximum for inhertiance depth?