1

我有两张桌子。

第一个表是成员表

MEMBER TABLE
ID    |  NAME
1     |  User
2     |  Another User
3     |  Some other User

第二张桌子是朋友

FRIENDS TABLE
ID    |  member_id    |  Friend Name    |  Notified
1     |  1            |  Friend #1      |  0
2     |  1            |  Friend #1      |  1
3     |  2            |  Friend #1      |  0
4     |  1            |  Friend #1      |  1
5     |  2            |  Friend #1      |  1

我喜欢做的是获取成员表信息,同时也获取每个成员的通知好友总数。

到目前为止我所做的是

SELECT
    M.ID
    M.NAME
    COUNT(F.notified)
FROM
    MEMBER AS M
LEFT JOIN
    FRIENDS AS F
ON
    F.member_id = M.id
WHERE
    F.notified = 1
GROUP BY
    M.id

但这对我不起作用,因为如果我有一个未通知朋友的成员,则查询不会包含在结果中。

例如,在上面的代码中,ID 为 3 的成员不会包含在我的结果中。

关于如何修改该查询以返回没有通知朋友的成员的任何想法?

亲切的问候梅里亚诺斯尼科斯

4

2 回答 2

5

WHERE F.notified = 1条件取消LEFT连接,使其作为INNER连接工作。将条件移至连接ON子句:

SELECT
    M.ID
    M.NAME
    COUNT(F.member_id)
FROM
      MEMBER AS M
  LEFT JOIN
      FRIENDS AS F
    ON
      F.member_id = M.id
    AND
      F.notified = 1
GROUP BY
    M.id ;
于 2012-07-07T08:40:14.100 回答
3

您可以通过这种方式使用子查询来做到这一点:

SELECT
    M.ID,
    M.NAME,
    (SELECT  COUNT(F.notified) FROM FRIENDS AS F WHERE F.member_id = M.id AND F.notified = 1) AS NUMFRIENDS
FROM
    MEMBER AS M 
GROUP BY
    M.id
于 2012-07-07T08:41:02.987 回答