有关计数的SQL问题

时间:2009-08-24 11:27:33

标签: sql mysql ruby-on-rails count aggregate

我想进行查询,以便我只能抓住至少有50个地方的地点。

我有一张地点表:

Id, City, Country
1, Austin, USA
2, Paris, France

通过Location_id连接到地点的地方信息表

Id, Name, Details, Location_id
1, The Zoo, blah, 2
2, Big Park, blah, 2

我可以这样加入他们:

SELECT places.name,places.id,locations.country,locations.city 从地方 INNER JOIN位置 ON places.location_id = locations.id

我怎样才能获得至少有50个地方的城市的结果,并以最大的数量订购?

谢谢!

4 个答案:

答案 0 :(得分:4)

使用GROUP BY with a HAVING条款。

SELECT locations.country, locations.city, COUNT(*)
FROM places
     INNER JOIN locations ON places.location_id = locations.id
GROUP BY locations.country, locations.city
HAVING COUNT(*) >= 50

答案 1 :(得分:3)

好的我已经看到上述答案几乎存在,但有一些错误,所以只需发布正确的版本:

SELECT locations.country, locations.city, COUNT(*) as count_of_places
FROM places
     INNER JOIN locations ON places.location_id = locations.id
GROUP BY locations.country, locations.city
HAVING COUNT(*) >= 50
ORDER BY count_of_places;

答案 2 :(得分:1)

您可以使用having子句将这些行限制为聚合列的值。此外,MySQL允许您使用惰性group by,因此您绝对可以利用此功能:

select
    l.country,
    l.city,
    p.name,
    p.details,
    count(*) as number_of_places
from
    locations l
    inner join places p on
        l.id = p.location_id
group by
    l.id
having
    count(*) >= 50
order by
    number_of_places,
    l.country,
    l.city,
    p.name

答案 3 :(得分:0)

有点不了解,但应该有效:

  

SELECT places.name, places.id, sq.country, sq.city, sq.counter   FROM (SELECT Locations.id, country,city, count(*) as counter FROM Locations   JOIN Places ON (Locations.Id=Places.Location_id) GROUP BY locations.id HAVING count(*)&gt; = 50)AS sq JOIN Place ON(sq.id = Places.Location_id) ORDER BY counter DESC` < / p>

P.S。确切的语法可能因数据库而异,我不确定这是mysql - 是否兼容。