即将到来的用户在今天和x天之间的生日

时间:2017-10-13 09:45:10

标签: mysql

我正在尝试使用以下查询进行简单的MySQL查询以显示即将到来的生日。如何排除/删除之前(昨天)的日期。

CREATE TABLE users (
  name VARCHAR(100),
  birthday DATE
);
INSERT INTO users (name, birthday) VALUES 
  ('kostas',  '1983-10-08'),
  ('kostas',  '1983-10-11'),
  ('yannis',  '1979-10-13'),
  ('natalia', '1980-10-15'),
  ('kostas',  '1983-10-12'),
  ('Moskas',  '1978-10-14'),
  ('Rasman',  '1978-10-13'),
  ('natalia', '1980-10-18'),
  ('natalia', '1980-10-16');

查询:

SELECT *
FROM 
  users 
WHERE 
  birthday != '' AND ABS(DAY(CURDATE()) - DAY(birthday)) < 2
ORDER BY 
  DAY(birthday)

演示:sqlfiddle

3 个答案:

答案 0 :(得分:2)

您必须使用BETWEEN代替ABS。绝对值不会返回您想要的内容,即生日前的0到&#34;天后#34; (2)是直到生日的正确方式。

你还必须使用DAYOFYEAR而不是DAY,你必须颠倒减法术语的顺序DAYOFYEAR(birthday) - DAYOFYEAR(CURDATE())

为了解决闰年生日问题,按照建议here,生日年应转换为当前年份:

DAYOFYEAR(DATE_ADD(e.birthdate, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR))

最终的SQL是:

SELECT *
FROM 
  users 
WHERE 
  birthday != '' AND (DAYOFYEAR(DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR))-DAYOFYEAR(CURDATE())) between 0 and 2
ORDER BY 
  DAY(birthday)

答案 1 :(得分:0)

我这样做: 将生日转移到当前年份,然后定义您想要的datediff

SELECT *,
       DATEDIFF(str_to_date(CONCAT(YEAR(curdate()), '-', MONTH(birthday), '-', DAY(birthday)), '%Y-%m-%d'), curdate()) AS `days until birthday`
FROM users
WHERE DATEDIFF(str_to_date(CONCAT(YEAR(curdate()), '-', MONTH(birthday), '-', DAY(birthday)), '%Y-%m-%d'), curdate()) BETWEEN 1 AND 5 ;

答案 2 :(得分:0)

我之前使用过这个,希望它会帮助别人。

SELECT name, birthday, DATE_ADD(birthday, INTERVAL IF(DAYOFYEAR(birthday) >= DAYOFYEAR(CURDATE()), YEAR(CURDATE())-YEAR(birthday), YEAR(CURDATE())-YEAR(birthday)+1) YEAR ) AS next_birthday 
FROM users
WHERE birthday!= '' AND disabled = '0'
HAVING next_birthday BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
ORDER BY next_birthday