MySQL Query to get age from date of birth

后端 未结 2 1329
眼角桃花
眼角桃花 2021-01-15 02:18

I have an issue with my query,

SELECT id, pseudo, nom, prenom, sexe, ville, 
       FLOOR(DATEDIFF (NOW(), date_naissance)/365) AS mAge 
FROM user 
WHERE sexe         


        
相关标签:
2条回答
  • 2021-01-15 02:30

    I use this query to get age of the user (years and months)

    SELECT 
    username
    ,date_of_birth
    ,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) DIV 12 AS years
    ,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) MOD 12 AS months
    FROM users
    

    Result as of today:

    chucknorris, 1979-04-10 00:00:00, 35, 2
    
    0 讨论(0)
  • 2021-01-15 02:47

    You can not use column aliases in WHERE clauses: http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html.

    You will have to rethink your query or change to:

    SELECT id, pseudo, nom, prenom, sexe, ville, 
       FLOOR(DATEDIFF (NOW(), date_naissance)/365) AS mAge 
    FROM user 
    WHERE sexe = 'Homme' AND 
    FLOOR(DATEDIFF (NOW(), date_naissance)/365) BETWEEN 18 AND 25 
    OR ville = 'Bordeaux'
    

    Ps you may also want to have a look at your ANDs and ORs as well as you might want to include some brackets.

    0 讨论(0)
提交回复
热议问题