左连接查询

时间:2017-02-02 00:24:02

标签: mysql sql left-join

我有以下查询

SELECT    table1.*, 
      table2.status
FROM      table1
LEFT JOIN table2 ON table1.transactionid = table2.transactionid
WHERE     table2.transactionid IS NULL   --Doesn't exist in table2
OR        table2.status = 2

如果table2中的同一个transactionid下面没有任何行,或者有一行但是状态= 2(错误)

,则返回table1行

现在我需要修改它,如果在table2中有一个具有相同transactionid且status = 1(已完成)的行,则不返回任何table1行

所以,可能有多个错误行,但如果有一个已完成,那么我不应该得到任何结果

enter image description here

谢谢

2 个答案:

答案 0 :(得分:1)

脑海中浮现出

Not exists

SELECT t1.*
FROM table1 t1
WHERE NOT EXISTS (SELECT 1
                  FROM table2
                  WHERE t1.transactionid = t2.transactionid AND
                        t2.status = 1
                 );

答案 1 :(得分:0)

使用' NOT IN'

SELECT t1。*
FROM table1 t1
在哪里t1.transactionid NOT IN(选择t2.transactionid
                      来自table2 t2
                  在哪里t1.transactionid = t2.transactionid和
                          t2.status = 1
                 );

或使用LEFT JOIN

SELECT t1。*
FROM table1 t1
LEFT JOIN table2 t2
ON t1.transactionid = t2.transactionid
WHERE.transactionid IS NULL