2012-05-04 47 views
1

計算行我有2個MySQL表:人&連接一個表中選擇部分和另一個

我要選擇從人的所有列,也算達到他們多少個連接在連接表。

-------------------- ---------------------- 
| People   | | Connections  | 
-------------------- ---------------------- 
| person_id | name | | cnt_id | person_id | 
-------------------- ---------------------- 

我想從人中選擇所有人並選擇該人的person_id在第二個表中出現的次數。

我一直想弄明白,但不能。希望你們都能幫忙。

謝謝!

+0

如果沒有連接的人,做你想做一個行數爲零,或者沒有行? –

+1

零計數的行。 – ATLChris

回答

2

如果沒有連接的人,這會給一排零計數:

SELECT 
    People.person_id, 
    People.name, 
    COUNT(Connections.person_id) AS number_of_connections 
FROM People 
LEFT JOIN Connections 
ON People.person_id = Connections.person_id 
GROUP BY People.person_id 
1

試試這個

SELECT name,count(Connection.person_id) as cnt FROM 
     People LEFT JOIN Connection ON People.person_id = Connection.person_id 
     GROUP BY Connection.person_id 
相關問題