SQL查询以找出最发挥作用的球队名称

时间:2018-09-21 16:17:15

标签: mysql sql

写一个查询以显示出参加最多比赛的球队的名称。如果有多个记录,请显示基于团队名称以升序排序的记录。

这是我的查询,我不知道如何使用游戏计数显示最大球队名称

select t.name,count(*) as game_count 
   from game g,team t 
   where (g.team_id_1 = t.id or g.team_id_2 = t.id) 
   group by t.name order by game_count desc;

我必须找到表现最出色的球队名称

我是MySQL的新手,因此无法找出正确/最有效的查询,请提供帮助。

具有列的游戏桌

ID GAME_DATE TEAM_ID_1 TEAM_ID_2

团队表具有列

ID NAME

3 个答案:

答案 0 :(得分:0)

这似乎有点涉及家庭作业问题。您可以使用表格表达式吗?

with summary as (
    select team_id, count(*) cnt from (
        select team_id_1 team_id from game union all
        select team_id_2 from game
    ) g
    group by team_id
)
select * from t where team_id in (
    select team_id from summary where cnt = (select max(cnt) from summary)
)
order by name;

答案 1 :(得分:0)

使用分组依据并带有子查询来匹配最大播放次数

select t.name as name, count(*) as gcount
from game g
join team t on t.id = g.team1 or t.id = g.team2 
group by t.name
having count(g.id) = (
    select count(g.id) games
    from game g
    join team t on t.id = g.team1 or t.id = g.team2 
    group by t.name
    order by games desc
    limit 1)

答案 2 :(得分:0)

select t.name from team t,game g where  t.id = g.team_id_1 or t.id = g.team_id_2  
  group by t.id having count(*) = (
  select max(cnt) from (select t.name,coalesce(count(*),0) cnt 
  from game g,team t 
  where  t.id = g.team_id_1 or t.id = g.team_id_2  group by t.id)a) 
  order by t.name;

解决了您的想法