[英]SQL question about counting
我想進行查詢,以便僅獲取具有至少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
我可以像這樣加入他們:
SELECT place.name,places.id,locations.country,locations.city FROM places INNER JOIN locations on place.location_id = location.id
我如何才能只獲得至少有50個位置的城市的結果並按最大數量排序?
謝謝!
將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
好的,我已經看到上面的答案差不多了,但是有一些錯誤,所以只發布正確的版本即可:
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;
您可以使用having
子句通過聚合列的值來限制這些行。 另外,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
表現不佳,但應該可以:
FROM (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平方加入Places ON(sq.id = Places.Location_id)
按櫃台DESC訂購
PS確切的語法可能會有所不同,具體取決於數據庫,我不確定這是否與mysql
兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.