简体   繁体   中英

mysql how to select records where condition by age

i am using a query where i need to select the rows from users where age between (multiple ages)

like i have 3 users in table users with 3 fields :

ID | NAME | DOB

1 | A | 12-06-1980
2 | B | 12-06-1970
3 | C | 12-06-1990
4 | D | 12-06-1995
5 | E | 12-06-1985

now if i want the list of users under 25 the out put

NAME | DATE OF BIRTH

C | 12-06-1990
D | 12-06-1995

What the query whould be for this any idea ?

SELECT * FROM users WHERE DOB 

? ANY IDEA

Try this ::

SELECT * FROM users WHERE DATEDIFF(CURDATE(), DOB)/365<25 

To get the age in years :

SELECT 
FLOOR(tempUsers.t/365) as `years`
tempUsers.t%365 as `months`
from
(
 SELECT DATEDIFF(CURDATE(), DOB) t FROM users 
) tempUsers
select *
from users
where DOB >= ADDDATE(CURRENT_DATE(), INTERVAL -25 YEAR);

You can do it like this:

SELECT * FROM users WHERE DOB >= (CURDATE() - INTERVAL 25 YEAR)

To calculate the 25 in above query from a dateofbirth date field, it would be as follows:

SELECT * FROM users 
WHERE DOB >= (CURDATE() - INTERVAL FLOOR(DATEDIFF(CURDATE(),dateofbirth)/365) YEAR)

I would use this:

select id, name, dob,
  date_format(curdate(), '%Y') - date_format(dob, '%Y') - 
  (date_format(curdate(), '00-%m-%d') < date_format(dob, '00-%m-%d')) as age
from users

it is more precise than dividing by 365, eg. this gives 2001 which is wrong:

SELECT floor(DATEDIFF('4012-12-12', '2012-12-12')/365)

while this gives 2000 which is correct:

select
  date_format('4012-12-12', '%Y') - date_format('2012-12-12', '%Y') - 
  (date_format('4012-12-12', '00-%m-%d') < date_format('2012-12-12', '00-%m-%d'))

if you just have to calculate just an age, however, both solutions should work.

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