18

我有 2 个简单的 mysql 表。第一个 1 称为 mail 并有 2 行:

sender | receiver
Marley | Bob 
Saget  | Bob 

第二个称为块并有 1 行:

blocker | blocked
  Bob   | Marley

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

sender 
 saget

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

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

2 回答 2

22

左连接将为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';
于 2013-03-20T19:15:35.400 回答
11

尝试这个:

SELECT sender
FROM mail m
WHERE NOT EXISTS (SELECT 1 FROM block 
                  WHERE blocker = m.receiver 
                  AND blocked = m.sender)
于 2013-03-20T19:19:02.190 回答