Mysql左连接:根据连接表中的另一个属性显示行

时间:2014-07-24 05:10:41

标签: mysql left-join

我有以下表格:

   Pools                         Members                             User
----------------------------------------------------------------------------------
id      name              id     pool_id     user_id              id      name
----------------------------------------------------------------------------------
1       abc               1         1          101                101     test1
2       xyz               2         1          102                102     test2
                          3         2          105                105     test5
                          4         2          106                106     test6

当用户登录时,他应该查看他不是其成员的那些池的列表,例如,如果id为101的用户登录,则应显示以下结果。

Pool              Members
xyz                2 members

1 个答案:

答案 0 :(得分:2)

你可能想要这个

SELECT name AS Pool,
       count(pool_id) AS Members
FROM Pools
JOIN Members ON Pools.id=Members.pool_id
WHERE Pool.id NOT IN
    (SELECT pool_id
     FROM Members
     WHERE user_id=101)
GROUP BY Member.pool_id