MySQL中的日期差计算年龄
我有一个关于 datediff
MYSQL 函数的问题,我可以使用它,而且很简单。但我不明白如何使用它来收集表字段内的差异。例如,
我有一个列dob
,我想编写一个查询来执行类似
select dateDiff(current_timeStamp,dob)
from sometable 'here dob is the table column
我的意思的事情,我想要从当前日期时间到表字段dob
的差异,每个查询结果是差值,即用户的年龄。
I have a problem regarding the datediff
MYSQL function, I can use it and it is simple. But I don't understand how to use it to collect differences within the table field. E.g.
I have a column dob
and I want to write a query that will do something like
select dateDiff(current_timeStamp,dob)
from sometable 'here dob is the table column
I mean I want the difference from the current date time to the table field dob
, each query result is the difference, the age of the user.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你是说像这样吗?
(来源 )
You mean like this?
(Source)
您可以这样做
SELECT TIMESTAMPDIFF(YEAR, date_of_birth, NOW()) AS
ageFROM your_table
每次都有效。
You could do this
SELECT TIMESTAMPDIFF(YEAR, date_of_birth, NOW()) AS
ageFROM your_table
Works everytime.
如果您想为每个用户显示年龄(以年为单位),请执行以下操作
If you want, for each user, display the age in years, do
如果我理解您对前面答案的评论,那么出生日期列实际上不是一个
DATE
值,而是一个格式为 m/d/y 的字符串。我强烈建议您更改此设置;它会减慢您想要执行的任何日期计算,并且您可能会面临将无效日期值输入到列中的风险。我想这就是你所需要的。它使用 STR_TO_DATE() 函数和 MySQL 文档中计算年龄的算法:
If I understand your comments on the previous answers, the date-of-birth column is not actually a
DATE
value but a string in the format m/d/y. I strongly recommend you change this; it slows down any date computations you want to do and you risk invalid date values getting entered into the column.I think this is what you need. It uses the
STR_TO_DATE()
function and an algorithm for computing the age from the MySQL documentation:我认为这应该有帮助
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;
注意:以正确的格式提供 DOB,例如
YYYY-MM-DD'=> '1991-11-11
I think this should help
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;
Note: Give the D.O.B in the correct format, E.g.
YYYY-MM-DD'=> '1991-11-11
试试这个
Try this