MySQL日期查找器从今天开始

时间:2011-11-29 08:51:09

标签: php mysql

我有一个用户表,其中包含生日的日期字段:

buddy_auto_id    int(11) PK

user_id          varchar(128)

buddy_user_id    varchar(128)

buddy_name       varchar(128)

buddy_bday       date

buddyuser_id     varchar(20)

active           enum('Yes','No')

requestsentby    int(11)

whenrequested    timestamp

我试图找到3个用户,他们的生日与今天的日期相比最快,然后首先显示他们的生日订购天数。

这在SQL查询中是否可行,或者我是否必须将其拉出来并让PHP执行这个等式?

非常感谢

3 个答案:

答案 0 :(得分:1)

我们首先需要计算下一个生日,然后按该值排序:

select *,
    buddy_bday + interval 
        if(
              month(buddy_bday) < month(now()) or 
              (month(buddy_bday) = month(now()) and day(buddy_bday) < day(now())),

              year(now())+1,
              year(now())
        ) - year(buddy_bday) year as next_bday
from buddies order by next_bday - date(now());

long if if语句判断好友今年是否已经过他/她的生日。

答案 1 :(得分:0)

这应该可以使用SQL。您需要将当前日期与从今年或明年表示的生日进行比较,具体取决于我们是否在当前年度过去了。获得此“下一个生日”日期后,请使用DATEDIFF函数确定距当前日期的天数。

SELECT *,
    DATEDIFF(
        # determine date of next birthday by adding age in years to birthday year
        DATE_ADD(buddy_bday, INTERVAL
            YEAR(CURDATE())-YEAR(buddy_bday)
            # add a year if we celebrated birthday already this year
            +(MONTH(buddy_bday)<MONTH(CURDATE()) OR (MONTH(buddy_bday)=MONTH(CURDATE()) AND DAY(buddy_bday) < DAY(CURDATE())))
        YEAR),
        CURDATE())
    AS days_to_next_bday
FROM user_table
ORDER BY days_to_next_bday
LIMIT 3;

答案 2 :(得分:-1)

您应该使用DAYOFYEAR函数。试试这个查询 -

SELECT buddy_auto_id , buddy_bday FROM table_name
  WHERE DAYOFYEAR(buddy_bday) - DAYOFYEAR(NOW()) > 0
  ORDER BY DAYOFYEAR(buddy_bday) - DAYOFYEAR(NOW())
  LIMIT 3;

因此,此查询仅适用于当前年份。


已编辑的查询2:

这个适用于所有日期。

CREATE TABLE birtdays(
  buddy_auto_id INT(11) NOT NULL AUTO_INCREMENT,
  buddy_bday DATE DEFAULT NULL,
  PRIMARY KEY (buddy_auto_id)
);

INSERT INTO birtdays VALUES 
  (1, '2011-10-04'),
  (2, '2011-03-01'),
  (3, '2011-11-29'),
  (4, '2011-11-10'),
  (5, '2011-12-29'),
  (6, '2011-11-30'),
  (7, '2011-12-08'),
  (8, '2011-09-17'),
  (9, '2011-12-01'),
  (10, '2011-12-11');

SELECT buddy_auto_id, buddy_bday
  FROM
    birtdays, (SELECT @day_of_year:=DAYOFYEAR(NOW())) t
  ORDER BY
    DAYOFYEAR(buddy_bday + INTERVAL YEAR(NOW()) - YEAR(buddy_bday) YEAR) - @day_of_year
      + IF (DAYOFYEAR(buddy_bday + INTERVAL YEAR(NOW()) - YEAR(buddy_bday) YEAR) - @day_of_year > 0, 0, DAYOFYEAR(STR_TO_DATE(CONCAT(YEAR(NOW()), '-12-31'), '%Y-%m-%d')))
  LIMIT 3;

+---------------+------------+
| buddy_auto_id | buddy_bday |
+---------------+------------+
|             6 | 2011-11-30 |
|             7 | 2011-12-08 |
|            10 | 2012-02-11 |
+---------------+------------+