首页 > 解决方案 > 有没有办法在不写两次左连接子查询的情况下逃脱?

问题描述

我的 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 倍以上的时间,而每次都没有返回任何结果。

回到问题,有没有什么方法可以不用写两次相当大的子查询

标签: sqloracle

解决方案


因为您没有从子查询中选择任何列,所以您可以将过滤移至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 可能无法对其进行优化。


推荐阅读