我有這個查詢,它回傳與這些表相交的所有記錄,但我想要表 1 中的更多列(比如 d、e、f),但這些列不存在于表 2 中。
(select a,b,c from tab1) where d<'31-dec21'
intersect
(Select a1,b1,c1 from tab2)
我應該使用什么查詢從 tab1 中獲取 a、b、c、d、e、f 列,在 tab2 中有 a=a1,b=b1 和 c=c1?
uj5u.com熱心網友回復:
使用子查詢:
select a, b, c, d, e
from tab1
where (a, b, c) in (select a, b, c from tab1 where d < date '2021-12-31'
intersect
select a1, b1, c1 from tab2
);
uj5u.com熱心網友回復:
INTERSECT可以重寫為 EXISTS 條件:
select tab1.*
from tab1
where d < '31-dec21'
and exists (select *
from tab2
where (tab1.a,tab1.b,tab1.c) = (tab2.a1,tab2.b1,tab2.c1))
uj5u.com熱心網友回復:
您的查詢做了兩件事:
- 選擇兩個表中存在的所有 a/b/c 元組
- 如果有任何重復項,請洗掉重復項(相比之下,
INTERSECT ALL請參閱https://docs.oracle.com/en/database/oracle/oracle-database/21/nfcon/details-enhanced-sql-set-operators-282451515.html對此)
IN因此,您可以從一個表中選擇并使用or查找另一個表中的行,EXISTS然后應用于DISTINCT結果:
select distinct a, b, c
from tab1
where d < date '2021-12-31'
and (a, b, c) in (select a1, b1, c1 from tab2);
這使您可以在不中斷查詢的情況下從 tab1 中選擇更多列。只需更換
select distinct a, b, c
經過
select distinct a, b, c, d, e, f
而且如果保證tab1中不能有重復的(a,b,c,d,e,f)元組,你甚至可以洗掉DISTINCT.
uj5u.com熱心網友回復:
嘗試這個
(select a,b,c,d,e,f from tab1) where d<'31-dec21'
intersect
(Select a1,b1,c1,null,null,null from tab2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448725.html
上一篇:<>''和<>''不起作用的情況
