帮助形成SQL语句

时间:2010-08-02 02:03:07

标签: sql mysql count group-by

我有两张桌子:景点和城市。景点包含一个名为city的列,它是对cities表中id的引用。我想形成一个MySQL语句,告诉我哪些城市的吸引力最大。

我知道我能做到:

SELECT COUNT(*) as `number` 
 FROM `attractions` 
WHERE `city` = XX 

...要计算一个城市中有多少景点,但是有一个声明可以计算每个城市的所有景点,并按景点数量的降序返回结果吗?

1 个答案:

答案 0 :(得分:3)

SELECT City.Name, COUNT(Attractions.City) as AttractionCount
FROM City
LEFT OUTER JOIN Attractions ON City.City = Attractions.City
GROUP BY City.Name
ORDER BY COUNT(Attractions.City) DESC