2014-03-05 380 views
0

答案的名單上有此DB:獲取每個城市

用戶表:

+----+---------+ 
| id | city_id | 
+----+---------+ 

city_id - >引用的城市ID

城市 - 表:

+----+------+ 
| id | city | 
+----+------+ 

回答表格:

+----+---------+ 
| id | user_id | 
+----+---------+ 

USER_ID - 對用戶

>引用ID現在,我想這個結果查詢:

+-----------+--------+ 
| City-name | amount | 
+-----------+--------+ 
| New York | 500 | 
+-----------+--------+ 

我試了幾個連接,計數,dinstincts但沒有成功。認爲它應該很容易,但沒有設法做到這一點。

我的查詢:

SELECT cities.name, COUNT(answers.id) FROM answers 
JOIN users ON users.id = answers.user_id 
JOIN cities on users.city_id = cities.id 

,但給了我只有1個城市..

+5

向我們顯示您的查詢。什麼意思是500(總數?)? – kmas

+0

你是如何得到'金額'欄的? –

+0

@kmas 500在該城市的答案 – Thijmen

回答

2

你應該聚合得到的計數等,所以是這樣的:

SELECT  COALESCE(c.city, '<Unknown>') AS Cityname, 
      COUNT(a.id) AS amount 

FROM  Answers AS a 

LEFT JOIN Users AS u 
    ON  a.user_id = u.id 

LEFT JOIN Cities AS c 
    ON  u.city_id = c.id 

GROUP BY c.city 
3

您需要添加GROUP BY cities.name

SELECT cities.name, COUNT(answers.id) FROM answers 
JOIN users ON users.id = answers.user_id 
JOIN cities on users.city_id = cities.id 
GROUP BY cities.name 

這將告訴MySQL你想讓COUNT按城市分組。如果沒有這個,mysql會把所有的東西都分組在一起並統計一切