2017-05-30 78 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

不客氣 –