小编典典

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

sql

我有2个简单的mysql表。前1个称为mail,具有2行:

sender | receiver
Marley | Bob 
Saget  | Bob

第二个称为块,并具有1行:

blocker | blocked
  Bob   | Marley

我想从发送鲍勃电子邮件但未在阻止表中阻止的第一个表中选择发件人。因此结果应为:

sender 
 saget

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

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

阅读 193

收藏
2021-03-23

共1个答案

小编典典

左联接将产生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';
2021-03-23