MySQL根據出生日期計算年齡的五種方法比較

2022-07-26 11:48:13 字數 2612 閱讀 3237

select date_format(from_days(to_days(now())-to_days(birthday)), '%y')+0 as age

方法一,作者也說出了缺陷,就是當日期為未來日期時結果為0,而不是負數;這裡使用了5個函式和兩個運算子。

select date_format(now(), '%y') - date_format(birthday, '%y') - (date_format(now(), '00-%m-%d') < date_format(birthday, '00-%m-%d')) as age

方法二,解決了方法一為負數的問題,但看起來更複雜;這裡使用了6個函式和3個運算子。

看了這篇貼子後,我就暈了,怎麼會這麼複雜,以前用sql server很簡單就可以了。我堅信一定有簡單高效的方法。很快就找到了根據以上方法改良後的方法。

select year( from_days( datediff( now( ), birthdate)));

select year(curdate())-year(birthday)-(right(curdate(),5)

改良後的方法一,少了乙個函式和乙個運算子,當日期為未來日期時計算結果還是為0;

改良後的方法二,還是6個函式和3個運算子,看起來簡單些;取日期的右邊五位,當日期格式為『2013-01-01』時取到的是『01-01』,沒有問題;當日期格式為『2013-1-1』縮寫格式時,取右邊的五位取出的是『3-1-1』,會導致出錯。

然後自己根據mysql的幫助文件中的日期函式想到了第三種方法:

select floor(datediff(curdate(), @birthday)/365.2422) 

取生日和當前日期之前的天數除以一年的實際天數(365天5小時48分46秒),然後取整。這樣只用了三個函式和乙個運算子就搞定了。

select  timestampdiff(year, @birthday, curdate()) 

這種方法只用了兩個函式就搞定了,應該是最佳方法了。

測試了一下以上四種方法,假如當前日期為'2017-1-13',當生日為『2013-1-14』時,還差一天就要過生日了,離4歲只 差一天了,結果還是3歲,感覺不是很合理;把方法三改造一下,四捨五入得到方法五:

select round(datediff(curdate(), @birthday)/365.2422) 

這樣計算出的年齡離實際的周歲最接近了,但可能方法四是最符合年齡定義的了。

mysql 生日有負數的處理

date_format(date_add(from_unixtime(0),interval a.birthday second),"%y-%m-%d") birthday

select '(-∞,20)' value,sum(case when user_age<20 then 1 else 0 end

) counts from (

select from_unixtime(birthday, '%y-%m-%d') as t_birth,curdate(), year(curdate())-year(from_unixtime(birthday, '%y-%m-%d') ) as user_age from wp_fuser where 1) ta

union

select '[20,30)' value,sum(case when (user_age>=20 and user_age<30) then 1 else 0 end

) counts from (

select from_unixtime(birthday, '%y-%m-%d') as t_birth,curdate(), year(curdate())-year(from_unixtime(birthday, '%y-%m-%d') ) as user_age from wp_fuser where 1) ta

union

select '[30,35)' value,sum(case when (user_age>=30 and user_age<35) then 1 else 0 end

) counts from (

select from_unixtime(birthday, '%y-%m-%d') as t_birth,curdate(), year(curdate())-year(from_unixtime(birthday, '%y-%m-%d') ) as user_age from wp_fuser where 1) ta

union

select '[35,+∞)' value,sum(case when user_age>=35 then 1 else 0 end

) counts from (

select from_unixtime(birthday, '%y-%m-%d') as t_birth,curdate(), year(curdate())-year(from_unixtime(birthday, '%y-%m-%d') ) as user_age from wp_fuser where 1) ta

mysql根據出生日期計算年齡

select date format from days to days now to days birthday y 0 as age方法一,作者也說出了缺陷,就是當日期為未來日期時結果為0,而不是負數 這裡使用了5個函式和兩個運算子。select date format now y date f...

SQL Server 根據出生日期計算年齡

getdate 函式用於返回當前的日期和時間 datediff 函式返回兩個日期之間的時間。語法 datediff datepart,startdate,enddate startdate 和 enddate 引數是合法的日期表示式。datepart 引數可以是下列的值 datepart縮寫年 yy...

oracle 根據出生日期計算精確年齡

select floor months between sysdate,to date 20141217 yyyy mm dd 12 a,手工輸入日期 months between sysdate,u.modifydate 12 b,從資料庫取值計算月份 floor months between s...