我有这个db:
用户表:
+----+---------+
| id | city_id |
+----+---------+
city_id - >引用城市上的ID
城市表:
+----+------+
| id | city |
+----+------+
解答表:
+----+---------+
| id | user_id |
+----+---------+
user_id - >引用用户ID
现在我想要一个包含此结果的查询:
+-----------+--------+
| City-name | amount |
+-----------+--------+
| New York | 500 |
+-----------+--------+
我尝试了几次连接,计数,直接但没有成功。认为它应该很容易,但没有设法做到。
我的查询:
SELECT cities.name, COUNT(answers.id) FROM answers
JOIN users ON users.id = answers.user_id
JOIN cities on users.city_id = cities.id
但只给我一个城市..
答案 0 :(得分: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会将所有内容组合在一起并统计一切。
答案 1 :(得分: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