关于计数的SQL问题
我想进行查询,以便只能获取至少有 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
我可以像这样加入它们:
SELECTplaces.name,places.id,locations.country,locations.city 来自地点 内连接位置 ON place.location_id =locations.id
by 如何才能只获取至少有 50 个地点的城市的结果,并按最大数量对它们进行排序?
谢谢!
I want to make a query so that I can grab only Locations that have at least 50 Places.
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
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
by how can I only get the results of cities that have at least 50 places and order them by the largest amount?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用带有 HAVING 子句的 GROUP BY 子句。
Use a GROUP BY with a HAVING clause.
好的,我已经看到上面的答案差不多了,但有一些错误,所以只发布正确的版本:
OK I've seen that the above answers are almost there but have some mistakes, so just posting the correct version:
您可以使用
having
子句通过聚合列的值来限制这些行。另外,MySQL 允许您使用惰性group by
,因此您绝对可以利用这一点:You can use the
having
clause to limit these rows by the value of an aggregate column. Also, MySQL allows you to use lazygroup by
s, so you can absolutely take advantage of this:性能有些不佳,但应该可以:
PS 确切的语法可能会因数据库而异,我不确定这是否与
mysql
兼容。Somewhat unperformant, but should work:
P.S. The exact syntax may vary depending on the database, I'm not sure if this is
mysql
-compatible as is.