简体   繁体   中英

What would be the best way to store birthdate(birthday) field with optional year

I have mysql database, with birthdate column as date.

What would be the best way to save into this column, with optional year. Should I just put some random year on it? what is the best practice to save birthday in database.

I create 3 text field in cakephp, day, month, and year.. but not sure how to approach this, to save in database, since if I randomly put the year (maybe 0001, since 0000 is not accepted), when I pull it back, it will show the year.

Might it be best to use three columns, Day, Month, and Year, and treat Year as optional?

Edit: Although using two might be cleaner. one DATE column and just put a dummy year in (0000) and one YEAR column. Then assemble the two as you use them. That way you get all the formatting, sorting and data validation that the data types provide, but you can still ignore the year when you don't have it

Just an opinion, but if the year is optional (some will have it; some won't) I'd use a DATE type and set the year to zero. You can check for birthdays without years like this:

SELECT * FROM myTable WHERE YEAR(birthdate) = 0

Or if the birthdate column is indexed use this instead because it'll be optimizable:

SELECT * FROM myTable WHERE birthdate <= '0000-12-31'

If the year is forbidden for all values - in other words you'll never store the year - I'd recommend separate month and day columns.

The best approach is to have two fields:

  1. birthdate which is a date
  2. BirthdayHasYear which is a flag (such as a tinyint)

The reason for not depending on a rule like "when the year is zero then it is unknown" is that the data structure is very hard to understand -- in the future or if someone else looks at it. I would then be inclined to add a constraint that said "if BirthDayHasYear is true then the year on birthdate is 0 (or whatever).

Alternatively, I would have one field of birthdate and then only access the table through a view where such fields as:

  • BirthdayHasYear
  • Age

are defined as additional fields in the view. In other databases, I would use this approach with computed columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM