MySQL左连接与第二个表上的计数

时间:2012-09-20 19:48:46

标签: mysql

我查看了本网站上的其他一些帖子,并没有看到我正在寻找的内容,所以这里就是这样。

假设我有2张桌子

juser
-----------------------------
userID   firstName   lastName
-----------------------------
1         billy        bob
2         jezze       belle
3         bobbie       sue

juserrel
--------------------------------------------- 
id       userID      relUserID        state
--------------------------------------------- 
1         1            2            approved
2         2            1            retired
3         2            1            approved
4         3            2            approved

我要做的是获取一个结果集,该结果集显示juser表中每个用户的每个用户信息,并在结果集中添加一个名为connections的列,显示特定用户与另一个用户有多少“活动”连接用户。

我希望根据上表得出的结果是

resultSet
-----------------------------------------------
userID    firstName    lastName    connections
-----------------------------------------------
  1         billy        bob           2
  2         jezze        belle         3
  3         bobbie       sue           1

我尝试的查询如下

select userID, firstName, lastName , coalesce(x.cnt,0) as connections 
from juser
left outer join (select count(*) cnt from juserrel where juserrel.userID =
userID or juserrel.relatedUserID = userID and juserrel.state = 'approved') 
x on userID = userID

我得到的结果集如下:

resultSet
-----------------------------------------------
userID    firstName    lastName    connections
-----------------------------------------------
  1         billy        bob           4
  2         jezze        belle         4
  3         bobbie       sue           4

请帮助;)

1 个答案:

答案 0 :(得分:3)

尝试:

select u.userID, u.firstName, u.lastName,
    count(case when ur.state = 'approved' then 1 end)
from juser u
inner join juserrel ur on u.userID = ur.userID or u.userID = ur.relUserID
group by u.userID, u.firstName, u.lastName

SQL Fiddle Example