【问题标题】:using order by and group by together in mysql在mysql中一起使用order by和group by
【发布时间】:2016-05-03 15:04:33
【问题描述】:

有一个名为 sample 的表,其中包含列名称和游戏。

name      games  
a        tennis  
b        tennis  
c        football  
d        shuttle  
e        basketball  
f        football  
g        football 

等等。

我需要前 2 个最常玩的游戏和前 2 个最少玩的游戏的列表。 如何同时使用 group by 和 order by?

【问题讨论】:

  • 游戏人数列在哪里
  • 为什么需要这样做?我们需要计算每场比赛的次数(可能使用 group by),然后我们需要使用 order by。但我不知道如何一起使用它们。 @NirpendraPatel
  • 你将如何查询最常玩的游戏
  • @NirpendraPatel 对于每个人,我猜数据表中都有一个新条目。
  • 我认为你不能在一个查询中同时选择最多和最少玩。

标签: mysql


【解决方案1】:

如果你想订购计数,你可以这样做

select count(*)  as num, games from sample 
group by games 
order by  num

前两个

select count(*)   as num, games from sample 
group by games 
order by  num limit 2

最后两个

select count(*)  as num, games from sample 
group by games 
order by  num DESC limit 2

【讨论】:

    【解决方案2】:
    select games, count(1) value
    from sample
    group by games order by value desc limit 2
    UNION ALL
    select games, count(1) value
    from sample
    group by games order by value limit 2
    

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多