我需要一个帮助构建一个mysql数据库的sql查询。 2表如下:
tblcities (id,name)
tblmembers(id,name,city_id)
现在我想要检索具有最多“成员”数量的“城市”详细信息。
此致
答案 0 :(得分:2)
SELECT tblcities.id, tblcities.name, COUNT(tblmembers.id) AS member_count
FROM tblcities
LEFT JOIN tblmembers ON tblcities.id = tblmembers.city_id
GROUP BY tblcities.id
ORDER BY member_count DESC
LIMIT 1
基本上:检索所有城市并计算每个城市有多少成员,按降序排列该成员数,先计算最高数量 - 然后只显示第一个城市。
答案 1 :(得分:1)
可怕,但这是一种做法:
SELECT * FROM tblcities WHERE id IN (
SELECT city_id
FROM tblMembers
GROUP BY city_id
HAVING COUNT(*) = (
SELECT MAX(TOTAL)
FROM (
SELECT COUNT(*) AS TOTAL
FROM tblMembers
GROUP BY city_id
) AS AUX
)
)
这样,如果有平局,你仍然可以获得所有会员人数最多的城市......
答案 2 :(得分:0)
Select ...
From tblCities As C
Join (
Select city_id, Count(*) As MemberCount
From tblMembers
Order By Count(*) Desc
Limit 1
) As MostMembers
On MostMembers.city_id = C.id
答案 3 :(得分:-1)
select top 1 c.id, c.name, count(*)
from tblcities c, tblmembers m
where c.id = m.city_id
group by c.id, c.name
order by count(*) desc