I have a column name 'dateEvent' in MySQL which stores date in the format '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)
My query
SELECT * FROM table WHERE DAYOFYEAR(dateEvent) < DAYOFYEAR(CURDATE()) ORDER BY DAYOFYEAR(dateEvent) DESC LIMIT 3")
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
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.
SELECT *
FROM (SELECT *
FROM elbat
WHERE dayofyear(dateevent) < dayofyear(curdate())
ORDER BY dayofyear(dateevent) DESC
LIMIT 3) AS x
ORDER BY dayofyear(dateevent) ASC;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.