简体   繁体   English

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

[英]Remove select subquery from column list to main query

Query 1 (Before):查询 1(之前):

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

结果查询 1

I want to remove the subquery from column level.我想从列级别删除子查询。 I modified the code to add join我修改了代码以添加加入

Query 2 (After):查询 2(之后):

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

结果查询 2

But if subquery returns blank (no value) then Query 1 returns data for ta.C1 and null for tb.C1 whereas Query 2 will return blank (no result).但是,如果子查询返回空白(无值),则查询 1 为 ta.C1 返回数据,为 tb.C1 返回 null,而查询 2 将返回空白(无结果)。 I want result of Query 2 as same as Query 1我希望查询 2 的结果与查询 1 相同

Why do you think your two queries are giving different responses?为什么您认为您的两个查询给出了不同的响应? They are equivalent:它们是等价的:

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 

The only difference with query 2 is that you're no longer benefiting from the scalar subquery caching you're getting in query 1. That may not matter if the ta.c2 column is unique or doesn't contain many repeated values.与查询 2 的唯一区别是您不再受益于您在查询 1 中获得的标量子查询缓存。如果 ta.c2 列是唯一的或不包含许多重复值,这可能无关紧要。

Both the queries are same.两个查询是相同的。 However in question queries and their output columns are different.但是,有问题的查询及其输出列是不同的。 There may be more conditions in your query that changes the output.您的查询中可能有更多条件会更改输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM