[英]SQL question about counting
I want to make a query so that I can grab only Locations that have at least 50 Places. 我想进行查询,以便仅获取具有至少50个位置的位置。
I have a table of Locations: 我有一张位置表:
Id, City, Country
1, Austin, USA
2, Paris, France
And a table of Places connected to Locations by Location_id 以及通过Location_id连接到Locations的Places表
Id, Name, Details, Location_id
1, The Zoo, blah, 2
2, Big Park, blah, 2
I can join them like so: 我可以像这样加入他们:
SELECT places.name, places.id, locations.country, locations.city FROM places INNER JOIN locations ON places.location_id = locations.id SELECT place.name,places.id,locations.country,locations.city FROM places INNER JOIN locations on place.location_id = location.id
by how can I only get the results of cities that have at least 50 places and order them by the largest amount? 我如何才能只获得至少有50个位置的城市的结果并按最大数量排序?
Thanks! 谢谢!
Use a GROUP BY with a HAVING clause. 将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
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;
You can use the having
clause to limit these rows by the value of an aggregate column. 您可以使用
having
子句通过聚合列的值来限制这些行。 Also, MySQL allows you to use lazy group by
s, so you can absolutely take advantage of this: 另外,MySQL允许您使用懒惰的
group by
s,因此您可以绝对利用此优势:
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
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 sqFROM (SELECT Locations.id, country,city, count(*) as counter FROM Locations
SELECT places.name, places.id, sq.country, sq.city, sq.counter
FROM (SELECT Locations.id, country,city, count(*) as counter FROM Locations
SELECT places.name, places.id, sq.country, sq.city, sq.counter
JOIN Places ON (Locations.Id=Places.Location_id)
GROUP BY location.id拥有计数(*)> = 50)AS平方JOIN Places ON (sq.id=Places.Location_id)
加入Places ON(sq.id = Places.Location_id)
ORDER BY counter DESC`
按柜台DESC订购
PS The exact syntax may vary depending on the database, I'm not sure if this is mysql
-compatible as is. PS确切的语法可能会有所不同,具体取决于数据库,我不确定这是否与
mysql
兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.