0

我想进行查询,以便我只能获取至少有 50 个地点的位置。

我有一张位置表:

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

以及按 Location_id 连接到 Locations 的 Places 表

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

我可以像这样加入他们:

选择places.name,places.id,locations.country,locations.city FROM places INNER JOIN locations ON places.location_id = locations.id

我怎样才能只获得至少有 50 个地方的城市的结果并按最大数量排序?

谢谢!

4

4 回答 4

4

GROUP BY 与 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
于 2009-08-24T11:31:35.880 回答
3

OK I've seen that the above answers are almost there but have some mistakes, so just posting the correct version:

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;
于 2009-08-24T11:45:27.317 回答
1

You can use the having clause to limit these rows by the value of an aggregate column. Also, MySQL allows you to use lazy group bys, so you can absolutely take advantage of this:

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
于 2009-08-24T11:37:34.247 回答
0

Somewhat unperformant, but should work:

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(*) >= 50) AS sq JOIN Places ON (sq.id=Places.Location_id) ORDER BY counter DESC`

P.S. The exact syntax may vary depending on the database, I'm not sure if this is mysql-compatible as is.

于 2009-08-24T11:37:21.797 回答