简体   繁体   English

有关SQL QUERY OF JOIN + COUNT + MAX的帮助

[英]Help with SQL QUERY OF JOIN+COUNT+MAX

I need a help constructung an sql query for mysql database. 我需要一个帮助构建一个mysql数据库的SQL查询。 2 Table as follows: 2表如下:

tblcities (id,name)
tblmembers(id,name,city_id)

Now I want to retrieve the 'city' details that has maximum number of 'members'. 现在,我要检索具有最大“成员”数量的“城市”详细信息。

Regards 问候

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

Basically: retrieve all cities and count how many members each has, sort by that member count in descending order, making the highest count first - then show only that first city. 基本上:检索所有城市并计算每个城市有多少成员,按降序排列该成员计数,首先计算最高数量 - 然后仅显示第一个城市。

Terrible, but that's a way of doing it: 糟透了,但这是一种方法:

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
    )
)

That way, if there is a tie, still you'll get all cities with the maximum number of members... 这样,即使有平局,您仍然可以获得所有会员人数最多的城市...

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
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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM