group-by - mysql中group by之后order by无效
怪我咯
怪我咯 2017-04-17 14:20:47
0
3
365

创建一张表(比如说帖子回复表,简单的几个字段)

create table replies(
    id int unsigned primary key auto_increment,
    uid int unsigned not null default 0,
    tid int unsigned not null default 0,
    content varchar(1000) not null default '',
    inputtime int unsigned not null default 0,
    updatetime int unsigned not null default 0
)engine myisam charset utf8;

插入数据

insert into replies
values
(null,3,4,'第四篇帖子的回复内容',1459848612,1459848612),
(null,4,1,'第一篇帖子的回复内容',1459858612,1459858612),
(null,3,3,'第三篇帖子的回复内容',1459868612,1459868612),
(null,5,1,'第一篇帖子的回复内容',1459878612,1459878612),
(null,1,5,'第五篇帖子的回复内容',1459888612,1459888612),
(null,2,5,'第五篇帖子的回复内容',1459898612,1459898612),
(null,8,2,'第二篇帖子的回复内容',1459908612,1459908612);

这样排序自然没什么问题

select tid,max(inputtime) as aa from replies group by tid order by aa desc;

然而

select tid,max(inputtime) from replies group by tid order by inputtime desc;

这样排序的话,结果却是这样

附个人理解:
这个max(inputtime)虽然和表上的数据是一样的,但它并不代表某个tid的inputtime,order by inputtime 实际是对表中的inputtime排序,所以这里看不到效果,但感觉这个理由有点牵强,请赐教,在这里谢谢诸位了

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
黄舟

https://segmentfault.com/a/1190000004879...
The correct understanding should be the three answers of shenyangyeshuai + 0808xyj + gzchen

小葫芦

In itself, these two are different SQLs. After grouping in MySQL, the first data is taken by default

黄舟

First of all, there is a problem with the semantics of the second statement. Since max (column) should not be sorted according to the original (column).
Then, you first understand the execution order of sql statements and your doubts will be solved
from -->join-->on-->where -->group by --> having --> select --> order by -->limit

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!