MYSQL计算年龄
想要根据生日获取用户年龄,使用了如下语句:
SELECT datediff(year,birthday, getdate()) as age
FROM users;
结果报错
Incorrect parameter count in the call to native function 'datediff'
原因是mysql中datediff只接受两个参数
改为如下:
SELECT datediff(birthday, getdate()) as age
FROM users;
结果报错
FUNCTION Mydb.getdate does not exist
将getdate()换成now()
SELECT datediff(birthday, now()) as age
FROM users;
注意:输出结果为负数,得到时间差数值是以秒为单位,调换参数位置即可
但我是要求年龄,所以最后使用另一种方法解决
SELECT TIMESTAMPDIFF(YEAR,birthday,NOW()) as age FROM users