doujiaochan7317 2015-03-26 18:36 采纳率: 0%
浏览 6
已采纳

对同一请求使用mysql GROUP BY和ORDER BY

I've been trying GROUP BY and ORDER BY in the same line to get what I want but it's not working. I am using a while loop that is running thousands of names, checking for highest points in each city. How do I get the name with highest points from each city, without repeating the same city twice?

This is what's in my database (in short):

ID City       Points    Name

1  NYC        16        Stan

2  London     24        Paul

3  NYC        11        Jeffrey

4  London     20        George

5  NYC        18        Ryan

$query = "SELECT `ID`, `City`, `Points`, `Name` FROM `table` GROUP BY `City` ORDER BY `Points`";

Gives me:

1 NYC 16 Stan

2 London 24 Paul

What I want it to give me:

2  London     24        Paul

5  NYC        18        Ryan
  • 写回答

2条回答 默认 最新

  • dongxuan1660 2015-03-26 18:48
    关注

    You can use left join as

    select t1.* from table_name t1 
    left join table_name t2 on t1.city=t2.city and t1.points < t2.points 
    where t2.id is null;
    

    Or using Uncorrelated subquery:

    select t.* from table_name t 
    join ( 
      select max(points) as points,city from table_name group by city
    )x on x.city=t.city and x.points = t.points ;
    

    Check the doc here https://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

    Or Subquery

    select t.* from table_name t 
    where not exists (
      select 1 from test t1 where t.city = t1.city and t.points < t1.points
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog