2017-05-30 239 views
1

我有两个表的用户和追随者的结果选择我需要得到用户的以下的数量和数量的追随者:合并两个PostgreSQL的表

用户:

id | name 
----+------ 
    1 | a 
    7 | b 
    2 | c 
    3 | d 
    4 | e 
    5 | f 
    6 | g 

追随者:

fid | uid 
-----+----- 
    1 | 7 
    1 | 2 
    1 | 6 
    1 | 3 
    7 | 1 

我试图做的:

SELECT id, name, count(fid) as following, count(uid) as followers 
FROM users 
INNER JOIN followers on users.id=followers.fid 
group by id; 

并得到错误的结果:

id | name | following | followers 
----+------+-----------+----------- 
    1 | a |   4 |   4 
    7 | b |   1 |   1 

附:我是干净的SQL语法的新手,请修复我的查询。

+2

看起来像你需要一个第二次加入id = uid的追随者数量。 –

+0

请举例。 – quas

+0

'SELECT id,name,count(fing.fid)如下所示,count(fers.uid)为关注者 FROM users u INNER JOIN follower fing on u.id = fing.fid INNER JOIN followers fers on u.id = fers.uid group by u.id;' –

回答

3

如果我理解正确的,你需要的是这样的:

select users.*, t1.following, t2.followers from users 
left join (select fid, count(*) as following from followers group by fid) t1 
on users.id = t1.fid 
left join (select uid, count(*) as followers from followers group by uid) t2 
on users.id = t2.uid 
-- where following is not null or followers is not null 

如果您需要排除的用户,谁不为以下和没有追随者,然后取消注释最后WHERE线

+0

谢谢,这是我需要的。 – quas

+0

不客气 –