使用SQL从类型为date的生日字段中获取年龄

时间:2013-06-17 11:12:18

标签: mysql sql database date

我在MySQL数据库中有一个表,其中包含date类型的字段。这里存储了用户的生日。是否有一种纯粹的SQL方法可以从现场选择年龄?

2 个答案:

答案 0 :(得分:2)

试试这个......

SELECT
    id,
    Name,
    DateofBirth,
    ((DATEDIFF(Cast((Select Now()) as Date),
    Cast(DateofBirth as Date)))/365) AS DiffDate
from TABEL1

编辑从Transact Charlie那里考虑事实......

 SELECT
        id,
        Name,
        DateofBirth,
        TIMESTAMPDIFF(Year, Cast(DateofBirth as Date),
        Cast((Select Now()) as Date)) AS DiffDate
    from TABEL1

答案 1 :(得分:1)

存储过程示例:

DATEDIFF(datepart, startdate, enddate)

更容易:

-- Declare Two DateTime Variable
Declare @Date1 datetime 
Declare @Date2 datetime 
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay