What is the best field to store the birthday?

后端 未结 5 811
我在风中等你
我在风中等你 2021-02-01 17:41

I have to store in my mysql database, the users\'s birthday ( like 12-11-1990 ).

What field type do I have to use to store it ?

5条回答
  •  逝去的感伤
    2021-02-01 17:58

    You can store it as a DATE object as you would normally do with non-repeating dates. The, if you're using MySQL (I believe other DBMS also have functions for this) you can retrieve birthdays using MySQL functions as described here:

    SELECT * 
    FROM table_name 
    WHERE 
        MONTH(date_field) = desired_month AND 
        DAY(date_field) = desired_day
    

    This method can be a bit slow when dealing with thousands of records. If that's your case, you can store the birthday with 3 separate INTs, one for each (year, month, day). Then you search birthdays like this:

    SELECT *
    FROM table_name
    WHERE
       month_field = desired_month AND
       day_field = desired_day
    

    If you use this last method, I'd advise you to also store a DATETIME version of the birthday so that you can build the date without any kind of maneuvers. You can additionally index each one of the 3 fields (non-unique) so it's faster to retrieve them.

提交回复
热议问题