我有两个表:“城市”和“提交”。
我想选择至少有n个提交内容的城市列表。最好的方法是什么?同样重要的是,大多数城市的提交数量将少于n个。
我已经尝试选择所有城市,然后通过对提交进行COUNT(*)查询来重新过滤列表,但这显然是一个非常低效的解决方案。任何帮助表示赞赏。
答案 0 :(得分:3)
试试这个:
SELECT Cities.id
FROM Cities
JOIN Submissions ON Cities.id = Submissions.CityId
GROUP BY Cities.id
HAVING COUNT(*) >= n
答案 1 :(得分:3)
select cityname, count(submissionid) as submissioncount
from cities inner join submissions
on submissions.cityid = cities.cityid
group by cityname
having count(submissionid) >= {yourdesiredcount}