MYSQL - 仅在LEFT JOIN中的行不存在时选择

时间:2013-03-20 19:12:52

标签: mysql sql database join

我有2个简单的mysql表。第一个叫做邮件,有2行:

sender | receiver
Marley | Bob 
Saget  | Bob 

第二个叫做block并且有一行:

blocker | blocked
  Bob   | Marley

我想从第一个表中选择发送Bob电子邮件但未在阻止表中阻止的发件人。所以结果应该是:

sender 
 saget

我尝试了以下查询,但它没有返回结果:

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = 'Bob') 
WHERE (block.blocked <> mail.sender)

2 个答案:

答案 0 :(得分:19)

左连接将为不匹配生成null行 这是您需要过滤的null行。

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = 'Bob') 
WHERE block.blocker IS NULL

加入一个固定值是一种扼杀,然而,一个更常见的连接(给定你的表)将是:

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = mail.receiver
                and block.blocked = mail.sender)<<-- these should match
WHERE block.blocker IS NULL                     <<-- select only mismatches
AND mail.receiver like 'bob';

答案 1 :(得分:10)

试试这个:

SELECT sender
FROM mail m
WHERE NOT EXISTS (SELECT 1 FROM block 
                  WHERE blocker = m.receiver 
                  AND blocked = m.sender)