mysql组内排序取最大值
admin
2023-05-20 14:42:56
0

最近业务反馈一个查询异常的问题,需要DBA对查询结果异常给出解释,并帮助他们解决该问题。问题本质是一个组内排序取最大值的问题,根据业务需求,我构建了测试用例

测试用例

--建表
create table testorder
(id int not null,
no int not null,
name char(10) not null,
primary key(id)
)engine=innodb;
--写入数据
insert into testorder values (1,1,'Mike'),(2,2,'John'),(3,3,'wyett'),(4,4,'Herry'),(5,5,'Mike'),(6,1,'John'),(7,2,'John'),(8,1,'Mike'),(9,1,'Mike');
--查询1
select * from testorder;
+----+----+-------+
| id | no | name  |
+----+----+-------+
|  1 |  1 | Mike  |
|  2 |  2 | John  |
|  3 |  3 | wyett |
|  4 |  4 | Herry |
|  5 |  5 | Mike  |
|  6 |  1 | John  |
|  7 |  2 | John  |
|  8 |  1 | Mike  |
|  9 |  1 | Mike  |
+----+----+-------+
--查询2
select * from testorder order by no desc;
+----+----+-------+
| id | no | name  |
+----+----+-------+
|  5 |  5 | Mike  |
|  4 |  4 | Herry |
|  3 |  3 | wyett |
|  2 |  2 | John  |
|  7 |  2 | John  |
|  1 |  1 | Mike  |
|  6 |  1 | John  |
|  8 |  1 | Mike  |
|  9 |  1 | Mike  |
+----+----+-------+
--查询3select * from (select id,no,name from testorder order by no desc)a group by a.name;

查询3这条SQL是我们需要讨论的内容,也是业务线为实现组内排序取最大值所采用的SQL。标准的程序员反馈问题方式:XXX时间点之前查询时正常的,这之后突然就不正常了,你们DBA是不是做什么改动了?我把数据恢复到自己的测试机,返回值也是正常的。暂且不去管姿势是否正确,对这条SQL的分析,我们其实可以看出:(1)程序员期待group by执行结果是按照临时表a的数据顺序来取值;(2)程序员未考虑版本因素,数据量变化的因素;为此,我构建了上面的测试用例。

测试

在不同版本的MySQL来进行测试:发现在Percona 5.5,Percona 5.1,MySQL 5.6关闭sql_mode= ONLY_FULL_GROUP_BY,MySQL5.1等版本下,返回值确如程序员期待的顺序,按照order by no desc的顺序,相同name返回no值最大的数据;

+----+----+-------+
| id | no | name  |
+----+----+-------+
|  4 |  4 | Herry |
|  2 |  2 | John  |
|  5 |  5 | Mike  |
|  3 |  3 | wyett |
+----+----+-------+

在mysql5.7,关闭sql_mode= ONLY_FULL_GROUP_BY和mariadb 10.*版本中,相同的name值,返回则是取了最早写入的数据行,忽略了order by no desc,按照数据的逻辑存储顺序来返回

+----+----+-------+
| id | no | name  |
+----+----+-------+
|  4 |  4 | Herry |
|  2 |  2 | John  |
|  1 |  1 | Mike  |
|  3 |  3 | wyett |
+----+----+-------+

其实在这里,SQL等价于select id,no,name from testorder group by name。
这里我们看出不同版本的返回值是不同的,先搁置数据量的变化引起执行结果不同的讨论,因为数据量大小很难测试。

官方文档

对上面的测试结果,在官方文档上,有如下的参考

If ONLY_FULL_GROUP_BY is disabled...In this case, the server is free to choose any value from each group, 
so unless they are the same, the values chosen are indeterminate, which is probably not what you want. 
Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. 
Result set sorting occurs after values have been chosen, and ORDER BY does not affect which value within 
each group the server chooses.

ONLY_FULL_GROUP_BY这个SQL_MODE出在mysql5.6(mariadb 10.0)时被引入,但本文讨论的内容和它无关,具体可以自己查看文档,这里不做讨论。在5.6,5.5的官方文档有相同的内容,Mariadb也有类似的解释

 If you select a non-grouped column or a value computed from a non-grouped column, it is undefined 
which row the returned value is taken from. This is not permitted if the ONLY_FULL_GROUP_BY SQL_MODE is used.

并且,对from后的subquery子表中的order by也给出了解释

 A query such as

SELECT field1, field2 FROM ( SELECT field1, field2 FROM table1 ORDER BY field2 ) alias
returns a result set that is not necessarily ordered by field2. This is not a bug.

A "table" (and subquery in the FROM clause too) is - according to the SQL standard - an unordered set of rows. 
Rows in a table (or in a subquery in the FROM clause) do not come in any specific order.

好了,有了这些解释,问题很明朗:

  • 在from 后的subquery中的order by会被忽略

  • group by cloumn返回的行是无序的

因此,业务获得的正确的返回值也是误打误撞。

解决办法

那么这个问题该怎么解决?

在网上有一些SQL,很明显不满足需求,在这里做一下展示,希望同学们避免被误导:

错误SQL集合

select id,sbustring(GROUP_CONCAT(distinct no order by no desc separator ''),'',1),name from testorder group by name;
--通过添加索引来影响返回的结果集顺序
alter table testorder add index idx_no_name(no desc, name);
--结果证明即使如此,desc也不会被正确执行;
--我司程序员的写法
select * from (select id,no,name from testorder order by no desc)a group by a.name
select id,max(no),name from testorder group by name

我们可以这样写,虽然效率不高

select a.id,a.no,a.name 
from testorder a 
inner join (select max(no) no,name 
            from testorder 
	    group by name) b on a.no=b.no and a.name=b.name 
group by name,no

或者这样

select a.id,a.no,a.name 
from testorder a 
group by a.name,a.no 
having a.no=(select max(no) from testorder where name=a.name)

 


相关内容

热门资讯

伊朗最好适可而止,见好就收 很多人都注意到中美这次达成的共识,抛开经贸层面的不谈,地缘及国际政治层面的,成果也是相当丰富。特朗普...
武大食堂爆满,学生无座可坐 5月13日,武汉大学正式取消社会公众进校预约制度。但校园开放后,不少学生在社交平台上发帖反映,部分游...
美以讨论重启对伊战事,特朗普:... 美国总统特朗普17日在社交媒体发文称,如果伊朗不迅速行动,“将一无所有”。特朗普写道:“对伊朗而言,...
张雪回应拿下第五冠:准备冲击年... 5月17日,2026世界超级摩托车锦标赛(WSBK)捷克站结束WorldSSP组别第二回合正赛争夺。...
特朗普就台湾问题表态 美国总统特朗普结束访华后,就台湾问题明确表态,不希望看到有人走向“独立”。
日防卫白皮书草案又炒“中国威胁... 【环球时报驻日本特约记者 初欣 环球时报记者 郭媛丹】日本政府2026年版《防卫白皮书》草案15日被...
47年,一条产业链托起一台冠军... 从嘉陵CJ50到张雪机车820RR——47年,一条产业链托起一台冠军摩托车(经济聚焦)本报记者 王欣...
核电站遭袭,阿联酋与卡塔尔、约... 当地时间17日,阿联酋强烈谴责针对位于宰夫拉地区巴拉卡核电站外围一台发电机的袭击。此次袭击由一架从西...
没处休、没空休、不敢休,保洁员... 一些商场、写字楼没有设置工间休息室,他们没空休息、无处休息——保洁员该在哪儿歇脚(金台视线)本报记者...
官方通报柳州5.2级地震:3人... 据中国地震台网正式测定,2026年5月18日00时21分,在广西柳州市柳南区发生5.2级地震。在此前...