我想在MYSQL中选择下一个即将到来的生日。 我的日期存储为:02/19/1981而不是日期字段。我认为它必须按天和月排序,而不是一年,但我不知道如何。
我该怎么做?这是迄今为止的查询:
$sql = "SELECT * FROM wp_postmeta WHERE meta_key='_web_date' ORDER BY ....";
答案 0 :(得分:1)
如果您可以将日期列更改为键入date。
否则试试这个:
SELECT month(str_to_date(birthdayColumn, "%m/%d/%Y")) as month, day(str_to_date(birthdayColumn, "%m/%d/%Y")) as day FROM yourTable order by month, day;
结果:
+-------+------+ | month | day | +-------+------+ | 1 | 12 | | 2 | 19 | | 9 | 10 | | 12 | 15 | +-------+------+
答案 1 :(得分:0)
您可以使用php date()函数。例如吃('Y-m-d',strtotime(“+ 7天”));然后创建一个sql查询,选择即将到来的7天内的日期
答案 2 :(得分:0)
这是一个测试环境。
CREATE TEMPORARY TABLE `birthdays` (
`id` int(4),
`name` VARCHAR(50),
`dob` CHAR(10)
) ENGINE=MEMORY;
INSERT INTO birthdays VALUES (1,'Alice', '02/19/1951'), (2,'Bob', '09/10/2015'), (3,'Carol', '12/15/2000'), (4,'Doug', '01/12/2011');
我创建了这个功能以获得下一个生日。这个逻辑可能会在2月29日/ 3月1日引发一些有趣的结果。
DELIMITER $$
CREATE FUNCTION `next_birth_day`(d_dob DATE) RETURNS DATE
DETERMINISTIC
BEGIN
/* NOTE: this logic ignores the handling of leap years */
/* MySQL will happily construct invalid leap years and they are ordered
between 29/2 & 1/3 in this code. */
DECLARE d_today DATE;
DECLARE d_this_year_bday DATE;
DECLARE d_next_year_bday DATE;
SET d_today = DATE(NOW());
SET d_this_year_bday = CONCAT(YEAR(d_today), '-', MONTH(d_dob), '-', DAY(d_dob));
SET d_next_year_bday = CONCAT(YEAR(d_today)+1, '-', MONTH(d_dob), '-', DAY(d_dob));
RETURN IF( d_this_year_bday < d_today, d_next_year_bday, d_this_year_bday);
END
$$
DELIMITER ;
然后你可以通过next_birth_day进行查询和排序:
SELECT *, str_to_date(dob, "%m/%d/%Y") AS dob_dt,
next_birth_day(str_to_date(dob, "%m/%d/%Y")) AS next_bday
FROM birthdays
ORDER BY next_birth_day(str_to_date(dob, "%m/%d/%Y")) ASC
给出这样的结果:
+------+-------+------------+------------+------------+
| id | name | dob | dob_dt | next_bday |
+------+-------+------------+------------+------------+
| 3 | Carol | 12/15/2000 | 2000-12-15 | 2015-12-15 |
| 4 | Doug | 01/12/2011 | 2011-01-12 | 2016-01-12 |
| 1 | Alice | 02/19/1951 | 1951-02-19 | 2016-02-19 |
| 2 | Bob | 09/10/2015 | 2015-09-10 | 2016-09-10 |
+------+-------+------------+------------+------------+