我有一个数据库表dates
,其中的列具有以下格式:
-------------------------
| id | name | day | month |
-------------------------
| 1 | matt | 7 | 3 |
| 2 | john | 2 | 1 |
| 3 | lily | 24 | 11 |
-------------------------
按月然后按日排序将数据拉出很容易,但是如何从今天的日期开始所有数据呢?
标准SQL:SELECT * FROM dates ORDER BY month ASC, day ASC
我认为我需要以某种方式使用CURDATE()
。
例如,今天是4月17日,因此我希望返回的数据如下:
-------------------------
| 3 | lily | 24 | 11 |
| 2 | john | 2 | 1 |
| 1 | matt | 7 | 3 |
-------------------------
由于11月24日是从今天开始的下一个日期,所以是1月2日,然后是3月7日。
答案 0 :(得分:1)
尝试一下。
这是2个子查询的并集。
SELECT
rslt.id,
rslt.name,
rslt.day,
rslt.month
FROM
(
(SELECT
a.*,
DATE_FORMAT(CURDATE(), '%m-%d') AS cdate,
CONCAT(
LPAD(`month`, 2, 0),
'-',
LPAD(`day`, 2, 0)
) AS bday,
1 AS rank
FROM
`dates` AS a
HAVING cdate <= bday
ORDER BY bday ASC)
UNION
(SELECT
b.*,
DATE_FORMAT(CURDATE(), '%m-%d') AS cdate,
CONCAT(
LPAD(`month`, 2, 0),
'-',
LPAD(`day`, 2, 0)
) AS bday,
2 AS rank
FROM
`dates` AS b
HAVING cdate > bday
ORDER BY bday ASC)
) AS rslt
ORDER BY rank ASC,
bday ASC ;
答案 1 :(得分:0)
此查询应该可以帮助您摆脱问题
(
SELECT DATE_FORMAT(CURDATE(), '%d') cur_day, DATE_FORMAT(CURDATE(), '%m') cur_month,`day`, `month`, 'current_year' title
FROM your_table
GROUP BY id
HAVING cur_day >= DAY AND cur_month >= month
ORDER BY `month` ASC, `day` ASC
)
UNION
(
SELECT DATE_FORMAT(CURDATE(), '%d') cur_day, DATE_FORMAT(CURDATE(), '%m') cur_month,`day`, `month`, , 'next_year' title
FROM your_table
GROUP BY id
HAVING cur_day < day and cur_month < month
ORDER BY `month` ASC, `day` ASC
)
首先,我要获取当年(即即将到来的日期)的所有行。
其次,我要获取所有已通过的行,并将在明年进行。
答案 2 :(得分:-1)
尝试一下
SELECT * FROM dates where day >= DAY(CURDATE()) ORDER BY month ASC, day ASC