简体   繁体   中英

How to calculate and apply condition on the age calculated based on date of birth in mysql?

I am calculating the user's age based upon his dob as:

SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),u.date_of_birth)), '%Y')+0 AS Age from users u ;

And it is giving me the correct age. Now how can I apply condition to. For eg when I am trying to do it,it is giving me error:

SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),u.date_of_birth)), '%Y')+0 AS Age from users u where age>20;

I know this syntax is incorrect but how can I apply condition to it in mysql and in JPA at Java side.

You can't use alias Age there directly in Where clause at it is not calculated at that stage. Instead, you need to use full expression (the same one you're using to calculate age in Select clause).

Following query should work:

   SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),u.date_of_birth)), '%Y')+0 AS Age 
   from users u 
   where DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),u.date_of_birth)), '%Y')+0 >20;

I think to understand this even better, you should know how an SQL query actually getting executed. Please go through this answer for the same.

Additionally, I think calculating Age at 2 places in same query is not the best way to do this. Suppose you have a unique column in table Users , and let's call it Id . Now, you can accomplish same with a better approach with following query:

Select u2.Id, u2.age
from users u1
inner join 
          (select id,
                  DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),u.date_of_birth)), '%Y')+0 AS Age 
           from users
          ) u2
On u1.id = u2.id
where u2.age > 20

Hope this helps!

To used it sql query in Java you need a preparedStatement or a statement . For prepared statement use those lines:

String sql = "SELECT * 
             FROM users
             WHERE date_of_birth > DATE_SUB(NOW(),INTERVAL ? YEAR);"

PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setInt(1, "20");
preparedStatement.executeQuery(sql);

Your query should be this one:

SELECT date_of_birth    
FROM users
WHERE date_of_birth > DATE_SUB(NOW(),INTERVAL 20 YEAR);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM