合并两个postgresql表中的select

时间:2017-05-30 18:35:45

标签: sql postgresql select count

我有两个表用户和关注者,我需要获得以下用户数量和关注者数量:

用户:

 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

P.S。我是干净的SQL语法的新手,请修复我的查询。

1 个答案:

答案 0 :(得分:3)

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

SNode

如果您需要排除不属于以下用户且没有关注者的用户,请取消注释上次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