SELECT * FROM (SELECT * FROM test ORDER BY seq DESC) tmp GROUP BY NAME
mysql5.7之后,会对组内排序优化,从而忽视组内排序,通过添加limit可以达到效果
SELECT * FROM (SELECT * FROM test ORDER BY seq DESC limit 10000000000) tmp GROUP BY NAME
原答案网址:网页链接
CREATE TABLE test
(
str VARCHAR(1),
time DATETIME
)
INSERT INTO ywtg.test (str, time) VALUES ('a', '2016-08-03 16:41:37')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-10 23:42:26')
INSERT INTO ywtg.test (str, time) VALUES ('a', '2016-08-13 23:42:46')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-14 23:42:58')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-15 23:43:13')
如上是表结构和数据,**需求:组与组之间按时间从大到小排序,组内数据按从小到大排序.**
如上数据也就是b组在a组前,b组和a组 组内数据又按从小到大排序,实现sql如下:
SELECT tt.*
FROM test tt LEFT JOIN (
SELECT
@rownum := @rownum + 1 AS rownum,
test.str
FROM (SELECT @rownum := 0) r, (SELECT str
FROM test
GROUP BY str
ORDER BY time DESC) test
) aa ON tt.str = aa.str
ORDER BY aa.rownum, time
你写的语句是先排序再分页的。如果你认为不是,就加个子查询:
select * from (select * from tabel as tb order by tb.price desc) temp_table limit 0,20。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)