根据列值取消连接条件

时间:2016-07-21 12:53:22

标签: sql sql-server join

我陷入了需要执行条件连接的情况。简要总结可以是,我有2个表TableATableB

TableA包含A1A2A3A4A5Condition1,{{1}列}

同样Condition2TableBB1B2Condition1

我需要在Condition2上执行联接并在TableA.Condition1 = TableB.Condition1上条件加入,对于任何记录首次加入,条件TableA.Condition2 = TableB.Condition2不应为空。

换句话说,如果某个TableA.Condition2匹配并同时TableA.Condition1 = TableB.Condition1的任何记录对于其中任何一个都不为空,则执行第二次加入,否则不执行第二次加入

查询可能就像

TableA.Condition2

3 个答案:

答案 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')
;