简体   繁体   English

我可以用任何类型的连接替换 Union all 吗?

[英]Can I replace Union all with any kind on joins?

I have the below query for negative testing, But I want to replace the union all if possible.我有以下关于负面测试的查询,但如果可能的话,我想union all

select A.*
from A
join B
on A.COL1=B.COL1
where B.COL3 is null

union all

select A.*
from A
join B
on A.COL2=B.COL4
where B.COL5 is null;

Need to get data from both SQL without using union all需要在不使用union all的情况下从 SQL 获取数据

You could combine the two queries into a single join and collapse the where condition into it:您可以将两个查询组合成一个连接并将where条件折叠到其中:

select A.* 
from   A 
join   B on (A.COL1 = B.COL1 and B.COL3 is null) or 
            (A.COL2 = B.COL4 and B.COL5 is null)
SELECT A.* 
FROM A 
JOIN B ON (A.COL1 = B.COL1 OR A.COL2 = B.COL4) AND B.COL3 IS NULL;

Since you're only after data from Table A you don't need the join to table B at all and can re-write this as an Exists...由于您只是在获取表 A 中的数据之后,您根本不需要连接到表 B,并且可以将其重写为 Exists ...

SELECT A.*
FROM A
WHERE EXISTS (SELECT 1 
              FROM B 
              WHERE A.COL1=B.COL1 and B.COL3 is null)
   OR EXISTS (SELECT 1 
              FROM B 
              WHERE A.COL2=B.COL4 and B.COL5 is null)

But this has likely has two issues:但这可能有两个问题:

  1. I'm pretty sure if you look at the execution plan for both;我很确定您是否查看了两者的执行计划; you'll find the union all is more efficient because it operates at a set level instead of a row level ad the OR needed in this is slower.您会发现 union all 效率更高,因为它在设定级别而不是行级别上运行,并且 OR 所需的速度较慢。
  2. This will return 1 record from A instead of 2 from that of a union all.这将从 A 返回 1 条记录,而不是从 union all 返回 2 条记录。 had it been a union;如果它是一个工会; this should/would return the same results and avoid the union.这应该/将返回相同的结果并避免合并。 But simply put you want the same data from A twice (or more depending on cardinality of joins)但简单地说,你想要两次来自 A 的相同数据(或更多取决于连接的基数)

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

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