【问题标题】:SQL query to find team name which played mostSQL查询查找出场次数最多的球队名称
【发布时间】:2018-09-21 16:17:15
【问题描述】:

编写查询以显示已进行最多比赛的球队的名称。如果有多个记录,则显示按团队名称升序排列的记录。

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

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

【问题讨论】:

  • 您的查询有什么问题?
  • 请不要发布屏幕截图,而是代码/表格结构以及@jens评论
  • 附注:不要使用逗号分隔的连接。在 MySQL 发明之前,它们就已经过时了。使用正确的连接:from game g join team t on t.id in (g.team_id_1, g.team_id_2).

标签: mysql sql


【解决方案1】:

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

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;

【讨论】:

  • type With 在低于 8 的 MySQL 版本中不受支持,如何找到最大值。这不是家庭作业,但我需要逻辑来查找最大总和属于某个 id,例如我提出这个问题的目的
【解决方案2】:

使用 group by 和 with 子查询来匹配最大播放次数

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)

【讨论】:

  • tq 但如果最大计数为不同的团队名称重复,则不要使用限制条件。
  • @LearningCenter 你是什么意思?如果两支比赛最多的球队都打了 5 场比赛,那么在子查询中限制指的是哪支球队有什么关系,计数 (5) 是返回的唯一有趣的结果。
  • 如果两个团队的计数都有 (5) 意味着必须打印两个团队
  • @LearningCenter 是的,我的查询就是这样做的。
【解决方案3】:
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;

已解决,感谢您的想法

【讨论】:

  • count() 从不返回 null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多