0

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

username
  Bob

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

sender | receiver
Marley | Bob
 Saget | Bob 

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

blocker | blocked
 Marley | Bob

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

users.username | count_mail 
 Bob           |  1 

因此,正如您所看到的,我需要让 Bob 以及他收到的消息数量只有 1 条,因为 Bob 阻止了 Marley,所以 Saget 的消息应该是唯一的 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)

谢谢

4

2 回答 2

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)
      )

或者

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)
于 2013-03-20T20:08:54.303 回答
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 子句品尝非连接断言。

于 2013-03-20T20:21:56.413 回答