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 docker环境配置
  • ¥20 绿盟安全扫描--检测到目标站点存在javascript框架库漏洞
  • ¥30 Android STD快速启动
  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现