Sort upcoming birthdays based on current date

后端 未结 5 950
庸人自扰
庸人自扰 2020-12-06 08:01

I have the following table of people and their birthdays:

name        birthday
----------------------
yannis      1979-06-29
natalia     1980-08-19
kostas            


        
5条回答
  •  时光说笑
    2020-12-06 08:30

    SELECT name
         , birthday
    FROM TableX
    ORDER BY DAYOFYEAR(birthday) < DAYOFYEAR(CURDATE())
           , DAYOFYEAR(birthday)
    

    No, the above may produce error results, due to years with 366 days. This is correct:

    SELECT name
         , birthday
    FROM
      ( SELECT name
             , birthday
             , MONTH(birthday) AS m
             , DAY(birthday) As d
        FROM TableX
      ) AS tmp
    ORDER BY (m,d) < ( MONTH(CURDATE()), DAY(CURDATE()) )
           , m
           , d
    

    If your table grows to more than a few thousands records, it will be real slow. If you want a fast query, add fields with the month and day and have an index on (bmonth,bday) or add them as one field, either Char (08-17 or 0817 for 17-Aug) or Int (817 for 17-Aug) and an index on that field.

提交回复
热议问题