我陷入了需要执行条件连接的情况。简要总结可以是,我有2个表TableA
和TableB
。
TableA
包含A1
,A2
,A3
,A4
,A5
,Condition1
,{{1}列}
同样Condition2
列TableB
,B1
,B2
,Condition1
我需要在Condition2
上执行联接并在TableA.Condition1 = TableB.Condition1
上条件加入,对于任何记录首次加入,条件TableA.Condition2 = TableB.Condition2
不应为空。
换句话说,如果某个TableA.Condition2
匹配并同时TableA.Condition1 = TableB.Condition1
的任何记录对于其中任何一个都不为空,则执行第二次加入,否则不执行第二次加入
查询可能就像
TableA.Condition2
答案 0 :(得分:0)
您只是从TableA
中选择,那么如何使用exists
呢?
SELECT A.*
FROM TableA A
WHERE (A.Condition2 IS NULL AND
EXISTS (SELECT 1 FROM TableB b WHERE A.Condition1 = B.Condition1)
) AND
(A.Condition2 IS NOT NULL AND
EXISTS (SELECT 1 FROM TableB b WHERE A.Condition1 = B.Condition1 AND A.Condition2 = B.Condition2)
);
或者,如果您想要JOIN
:
SELECT A.*
FROM TableA A JOIN
TableB B
ON A.Condition1 = B.Condition1 AND
(A.Condition2 IS NOT NULL OR A.Condition2 = B.Condition2);
答案 1 :(得分:0)
试试这可能会对你有所帮助
SELECT A.*
FROM TableA A
INNER JOIN TableB B ON A.Condition1 = B.Condition1 AND
((A.Condition2 IS NOT NULL AND A.Condition2 = B.Condition2)
OR (A.Condition2 IS NULL) )
答案 2 :(得分:0)
很难理解你的问题,甚至更难理解目的
SELECT A.*
-- join table1 and table2 on Condition1
FROM TableA A
JOIN TableB B ON A.Condition1 = B.Condition1
-- if max condition2 is null then there is nothing but nulls
JOIN ( SELECT MAX(Condition2) Condition2 FROM TableA A2 ) A2
-- in that case every row resulting from join1 goes
ON A2.Condition2 IS NULL
-- otherwise use condition2 but replace nulls with some placeholder
-- or maybe you have either all null or no nulls
OR COALESCE (A.Condition2,'null') = COALESCE (B.Condition2,'null')
;