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

时间:2015-03-26 18:36:50

标签: php mysql sql mysqli

我一直在同一行尝试GROUP BYORDER BY来获得我想要的东西,但它不起作用。 我正在使用一个运行数千个名字的while循环,检查每个城市的最高点。 如何从每个城市获得最高分的名称,而不是两次重复同一个城市?

这就是我的数据库中的内容(简称):

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`";

给我:

1 NYC 16 Stan

2 London 24 Paul

我希望它能给我:

2  London     24        Paul

5  NYC        18        Ryan

2 个答案:

答案 0 :(得分:1)

那是groupwise maximum,是最常见的SQL问题之一。 你可以尝试这样的事情,

SELECT tab1.*
FROM @Table AS tab1
LEFT JOIN @Table AS tab2 
     ON tab1.City=tab2.city  AND tab2.points > tab1.points
WHERE tab2.City IS NULL;

答案 1 :(得分:1)

您可以使用左连接作为

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;

或使用Uncorrelated子查询:

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 ;

查看此处的文档https://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

或子查询

select t.* from table_name t 
where not exists (
  select 1 from test t1 where t.city = t1.city and t.points < t1.points
);