简体   繁体   English

查询按降序排列时如何按事件日期升序排序 MySQL

[英]How to sort by event date asc when query is in descending order MySQL

I have a column name 'dateEvent' in MySQL which stores date in the format 'Ym-d':我在 MySQL 中有一个列名“dateEvent”,它以“Ym-d”格式存储日期:

+-------------+
| dateEvent   |
|-------------+
| 2018-01-01  |
| 2022-01-02  |
| 2021-01-03  |
| 2019-01-04  |
| 2016-01-05  |
| 2018-01-06  |
| 2020-01-07  |
| 2017-01-08  |
| 2021-01-09  |
| 2015-01-10  |
| 2016-01-11  |
| 2019-01-12  |
| 2018-01-13  |
| 2021-01-14  |
+-------------+

I need to output 3 nearest day right before today (6-jan) regardless of the year (5-jan, 4-jan and 3-jan) and they be sorted in ascending order (3-jan, 4-jan, 5-jan)我需要 output 3 最近一天(1 月 6 日),无论年份如何(1 月 5 日、1 月 4 日和 1 月 3 日),它们按升序排序(3 月、4 日、5-一月)

My query我的查询

SELECT * FROM table WHERE DAYOFYEAR(dateEvent) < DAYOFYEAR(CURDATE()) ORDER BY DAYOFYEAR(dateEvent) DESC LIMIT 3")

Output: Output:

2016-01-05 |                      | 2021-01-03
2019-01-04 | -->I want there are: | 2019-01-04
2021-01-03 |                      | 2016-01-05

When i change ORDER to ASC, output is当我将 ORDER 更改为 ASC 时,output 是

2018-01-01 |
2022-01-02 |  incorrect with my request
2021-01-03 |

How can I do?我能怎么做? Any help will be appreciated.任何帮助将不胜感激。

Try to order by:尝试通过以下方式订购:

ORDER BY DATE_FORMAT(dateEvent, '%m-%d')

or或者

ORDER BY MONTH(dateEvent), DAYOFMONTH(dateEvent)

Well, the probably simplest way is to just get the LIMIT ing done in a derived table and apply another ORDER BY in the outer query.好吧,可能最简单的方法是在派生表中完成LIMIT并在外部查询中应用另一个ORDER BY

SELECT *
       FROM (SELECT *
                    FROM elbat
                    WHERE dayofyear(dateevent) < dayofyear(curdate())
                    ORDER BY dayofyear(dateevent) DESC
                    LIMIT 3) AS x
       ORDER BY dayofyear(dateevent) ASC;

db<>fiddle db<>小提琴

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

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