【问题标题】:Merge select from two postgresql tables从两个 postgresql 表中合并选择
【发布时间】:2017-10-31 08:35:55
【问题描述】:

我有两个表用户和关注者,结果我需要获取用户的关注数量和关注者的数量:

用户:

 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 语法的新手,请修复我的查询。

【问题讨论】:

  • 看起来您需要在 id = uid 上再次加入以获取关注者数量。
  • 请举例。
  • SELECT id, name, count(fing.fid) as following, count(fers.uid) as followers FROM users u INNER JOIN followers fing on u.id=fing.fid INNER JOIN followers fers on u.id=fers.uid group by u.id;
  • 我之前做过类似的事情,但得到了错误的结果。您的样品返回 1 |一个 | 8 | 8
  • @otoshavadze 在下面有一个很好的答案。我不精通 postgres 语法,所以我不是 100% 有信心给你一个好的答案。

标签: sql postgresql select count


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这正是我需要的。
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
相关资源
最近更新 更多