我正在尝试编写查询以选择其生日在未来7天内的数据库用户。
我已经做了很多研究,但无法提出可行的解决方案。
生日字段存储为varchar,例如‘04 / 16/93’,有什么办法可以使用?
这是我到目前为止的内容:
SELECT * FROM `PERSONS` WHERE `BIRTHDAY` > DATEADD(DAY, -7, GETDATE())
我应该说得更清楚一些,我想找到生日而不是生日。所以我只是在寻找几天和几个月而不是几年。
要获得接下来7天内的所有生日,请将出生日期和今天之间的年份差值与出生日期相加,然后查找是否在接下来的7天内。
SELECT * FROM persons WHERE DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) + IF(DAYOFYEAR(CURDATE()) > DAYOFYEAR(birthday),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY);
如果要排除今天的生日,请更改>为>=
>
>=
SELECT * FROM persons WHERE DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) + IF(DAYOFYEAR(CURDATE()) >= DAYOFYEAR(birthday),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY); -- Same as above query with another way to exclude today's birthdays SELECT * FROM persons WHERE DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) + IF(DAYOFYEAR(CURDATE()) > DAYOFYEAR(birthday),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) AND DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) YEAR) <> CURDATE(); -- Same as above query with another way to exclude today's birthdays SELECT * FROM persons WHERE DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) + IF(DAYOFYEAR(CURDATE()) > DAYOFYEAR(birthday),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) AND (MONTH(birthday) <> MONTH(CURDATE()) OR DAY(birthday) <> DAY(CURDATE()));
这是所有查询的演示