简体   繁体   English

MySQL ORDER BY两次(通过同一字段)

[英]MySQL ORDER BY Twice (by same field)

I have a series of events with dates, as follows: 我有一系列带有日期的事件,如下所示:

  • Event 1, 1/1/2014 活动1,1 / 1/2014
  • Event 2, 1/2/2014 事件2,2014年1月2日
  • Event 3, 1/3/2014 事件3,1/3/2014

Say I wanted the most recent two events, in chronological order. 假设我想要按时间顺序排列的最近两个事件。 If I ran: 如果我跑了:

SELECT * FROM 'table_name' ORDER BY 'Date' ASC LIMIT 2

I would get the following results: 我会得到以下结果:

  • Event 1, 1/1/2014 活动1,1 / 1/2014
  • Event 2, 1/2/2014 事件2,2014年1月2日

But this is incorrect, as Event 3 is the most recent event. 但这是不正确的,因为事件3是最近发生的事件。 So I therefore change ASC to DESC: 因此,因此我将ASC更改为DESC:

SELECT * FROM 'table_name' ORDER BY 'Date' DESC LIMIT 2

And I get the following results: 我得到以下结果:

  • Event 3, 1/3/2014 事件3,1/3/2014
  • Event 2, 1/2/2014 事件2,2014年1月2日

This is the correct result set, but they're backwards. 这是正确的结果集,但它们是落后的。 I would like the most recent event last...but I can't simply use ORDER BY 'Date' a second time. 我想要最近的活动...但是我不能简单地第二次使用ORDER BY 'Date' Is there a way to limit my results (via a LIMIT and an ORDER BY , and then use a second ORDER BY on the remaining results? 有没有办法限制我的结果(通过LIMITORDER BY ,然后对其余结果使用第二个ORDER BY

Any help is much appreciated! 任何帮助深表感谢!

an even faster way is to just do one select. 更快的方法是只选择一个。 use UNION syntax to order a second time. 使用UNION语法进行第二次订购。 try it out! 试试看!

(SELECT * 
 FROM events 
 ORDER BY date DESC 
 LIMIT 2
)ORDER BY date ASC;

DEMO 演示

SELECT * 
FROM (SELECT * FROM events ORDER BY date DESC LIMIT 2) AS table_alias 
ORDER BY date ASC

You need to have a table alias for a sub query 您需要为子查询提供表别名

Cheers 干杯

actually, you can 其实你可以

SELECT * FROM (
SELECT * FROM 'table_name' ORDER BY 'Date' DESC LIMIT 2
)
ORDER BY 'Date' ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM