问题
I've already tried all other questions/solutions, and no answer. so here it is: I need to SELECT * FROM people WHERE
(dob is 18 to 40)
but my dob is stored as DATE
type YYYY-MM-DD
need to select people between 18 and 40 for example!
回答1:
You need to use BETWEEN
with some year calculation TIMESTAMPDIFF(YEAR,'1980-02-04',NOW())
SELECT * FROM people WHERE TIMESTAMPDIFF(YEAR,`dob`,NOW()) BETWEEN 18 AND 40
See fiddle here
TIMESTAMPDIFF
YEAR(date)
回答2:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
回答3:
You have to calculate 40 years ago from today, and 18 years ago from today. Let's say it was 1940-01-01
and 1980-01-01
, then it would be:
WHERE dob BETWEEN '1940-01-01' AND '1980-01-01';
回答4:
since I do not know the SQL dialect you use I take the full variant
since age
is now - birth (!)
select * from people where
current date - date(birth) > MINAGE
and
current date - date(birth) < MAXAGE
current date
depends on SQL you are using
回答5:
Since age is relative to today:
select * from people where
date_sub(curdate(), interval 40 year) =< dob
and date_sub(curdate(), interval 18 year) >= dob
This will work on any version of mysql
来源:https://stackoverflow.com/questions/20292631/how-select-people-within-age-range