从列列表中删除选择子查询到主查询

时间:2018-11-05 06:54:01

标签: sql oracle join subquery

查询1(之前):

select ta.C1,
       (SELECT tb.C1 from T2 tb WHERE  tb.C2 = ta.C2)
from T1 ta
WHERE ta.C3=30025239;

Result Query 1

我想从列级删除子查询。 我修改了代码以添加连接

查询2(之后):

select ta.C1, tb.C1
from T1 ta left outer join
     T2 tb 
     on tb.C2 = ta.C2
WHERE ta.C3=30025239;

Result Query 2

但是,如果子查询返回空白(无值),则查询1返回ta.C1的数据,而tb.C1返回null,而查询2将返回空白(无结果)。 我想要查询2的结果与查询1相同

2 个答案:

答案 0 :(得分:0)

您为什么认为您的两个查询给出的响应不同?它们是等效的:

WITH t1 AS (SELECT 1 c1, 10 c2, 30025239 c3 FROM dual UNION ALL
            SELECT 2 c1, 20 c2, 30025239 c3 FROM dual UNION ALL
            SELECT 3 c1, 30 c2, 30025238 c3 FROM dual),
     t2 AS (SELECT 100 c1, 10 c2 FROM dual UNION ALL
            SELECT 300 c1, 30 c2 FROM dual)
select 'query 1' qry, ta.C1 ta_c1, (SELECT tb.C1 from T2 tb WHERE  tb.C2 = ta.C2) tb_c1
from T1 ta WHERE ta.C3=30025239
UNION ALL
select 'query 2' qry, ta.C1, tb.C1
from T1 ta left outer join T2 tb on tb.C2 = ta.C2
WHERE ta.C3=30025239;

QRY          TA_C1      TB_C1
------- ---------- ----------
query 1          1        100
query 1          2 
query 2          1        100
query 2          2 

查询2的唯一区别是您不再从查询1中获得的标量子查询缓存中受益。如果ta.c2列是唯一的或不包含许多重复的值,则可能无关紧要

答案 1 :(得分:0)

两个查询都相同。但是,有疑问的查询及其输出列是不同的。您的查询中可能还有更多条件会更改输出。