如何存储生日和年龄,以便年龄可以在PHP / MySQL中每天更新? [英] How to store Birthdate and Age so that Age can be updated daily in PHP/MySQL?

查看:220
本文介绍了如何存储生日和年龄,以便年龄可以在PHP / MySQL中每天更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在MySQL中存储Birthdate,以便我可以通过Cron Job轻松更新每个人的年龄?

存储年龄和生日这一点也是有意义的,因此当涉及到年龄的搜索时,我不必计算每个年龄的动态和浪费CPU资源?

Does it even make sense to store the Age AND the Birthdate so that when searches involving the Age are made, I don't have to calculate each Age on-the-fly and waste CPU resources?

如果是这样,我应该如何1)存储生日,和2)每天计算年龄?

If so, how should I 1) store the Birthdate, and 2) calculate the Age each day?

我可以想象每日cron脚本首先过滤出用户的Birthdate月份不是当前月份,然后过滤出用户的Birthdate天不是当天,然后将每个用户的年龄增加一个。

I can imagine the daily cron script first filtering out the user's whose Birthdate month is not the current month, then filtering out the user's whose Birthdate day is not the current day, and then incrementing by one the age of each user that is left.

这是否有意义?如果是这样,我该怎么办?有没有更好的方法来做所有这些?

Does this make sense? If so, how would I do that? Is there a better way to do all of this?

推荐答案

简单的答案是不要;永远不会存储人的年龄。每个人每年都会发生变化,但如你所说,你必须检查每个人每天是否正确。

The simple answer is don't; never store a persons age. It changes for each person yearly but, as you say, you have to check that it's correct for every person daily.

只存储出生日期,然后计算从数据库中选择年龄。只有今天 - 出生日期所以几乎没有CPU。

Only store the date of birth, and then calculate the age when selecting from the database. It's only today - date of birth so takes almost no CPUs at all.

编辑:

为了扩展我在 ManseUK的答案中的评论,也有失败的可能性。如果您的服务器/数据库关闭会怎么样?或者您的更新无法在指定的时间运行?或者有人来了,在该日期的更新已经运行之后手动运行?还是有人关掉你的调度器?如果您从数据库中选择年龄,则不会发生这种情况。

To expand upon my comment in ManseUK's answer there's also the possibility of failure. What happens if your server / database is down? Or your update fails to run at its specified time? Or someone comes along and runs it manually after the update already been run for that date? Or someone turns off your scheduler? There's no danger of this happening if you calculate Age as you select from the database.

选择年龄在25到30年之间,假设DATE列 dateofbirth ,您的查询将如下所示:

To select where age is between 25 and 30 years and assuming a DATE column dateofbirth your query would be something like:

select *
  from users
 where dateofbirth between date_add( curdate(), interval -30 year )
                       and date_add( curdate(), interval -25 year )

确保用户 dateofbirth

这篇关于如何存储生日和年龄,以便年龄可以在PHP / MySQL中每天更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆