连接两个表并选择第二个中不存在的行1

时间:2013-03-20 20:02:32

标签: mysql sql database join

我有一个名为users的表,其用户名为Bob,如下所示:

username
  Bob

我有另一个名为mail的表,其中包含以下行:

sender | receiver
Marley | Bob
 Saget | Bob 

我有另一个名为block的表,其中包含以下行:

blocker | blocked
 Marley | Bob

我想从表用户中选择用户以及他们收到的邮件数量但是忽略来自被阻止用户的邮件。所以结果应该是这样的:

users.username | count_mail 
 Bob           |  1 

所以你可以看到我需要让鲍勃收到他收到的邮件数量,因为鲍勃阻止了马利只有1,所以萨格的信息应该是唯一的1。

我使用以下查询但它什么都不返回:

SELECT user, COUNT(mail) AS count_mail FROM users 
LEFT JOIN block ON (block.blocker = users.username) 
LEFT JOIN mail ON (mail.receiver = users.username 
                   AND mail.sender <> block.blocked)

由于

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT user, COUNT(mail) AS count_mail FROM users 
LEFT JOIN mail ON (mail.receiver = users.username)
WHERE (mail.sender is null 
         or NOT EXISTS
             (SELECT 1 FROM block 
              WHERE mail.sender = block.blocker
              AND mail.receiver = block.blocked)
      )

OR

SELECT user, COUNT(mail) AS count_mail FROM users 
LEFT JOIN (SELECT * FROM mail WHERE NOT EXISTS
                 (SELECT 1 FROM block 
                   WHERE mail.sender = block.blocker
                   AND mail.receiver = block.blocked)
          ) mail ON (mail.receiver = users.username)

答案 1 :(得分:1)

试试这个:

SELECT users.username, COUNT(mail.receiver) AS count_mail
FROM users 
LEFT JOIN mail ON mail.receiver = users.username 
LEFT JOIN block ON block.blocker = users.username
    AND mail.sender = block.blocked
WHERE block.blocked IS NULL
GROUP BY 1

这是有效的,因为只有当左连接到阻塞程序失败时它才会被命中 - 由where子句判断是否为非连接。