3

i have a table in MySQL database of people, with their Birthrates. for example '1991-11-21'

I have two values, one is minimum age(like 22), and the other is maximum age(like 33). I would like to make a query that gets me all the records with people between the minimum age value, and the maximum.

I am working with NodeJs. any ideas?

Dan The Man
  • 1,835
  • 6
  • 30
  • 50
  • what worked is the following: var myQuery = "SELECT Bdate FROM " +tableName+ " WHERE Bdate BETWEEN " + "DATE_SUB(NOW(),INTERVAL " +Info.maxAge+ " YEAR)" + " AND " +"DATE_SUB(NOW(),INTERVAL " +Info.minAge+ " YEAR)"; – Dan The Man Dec 16 '15 at 17:41

2 Answers2

2

One solution is to do all the work in MySQL and inject your variables into your MySQL statement

To do that you will need a combination of these answers

1) Get the date from x years ago

Selecting all records from one year ago till now

2) Select results between date range

Select mysql query between date?

You should end up with a query something like this:

select * 
from *table_name* 
where *datetime_column* 
between DATE_SUB(NOW(),INTERVAL 22 YEAR)
and DATE_SUB(NOW(),INTERVAL 33 YEAR);

Note: you may need to add a year to the second date (33+1) to get the full range of someones age being 33 (you are 33 until the day you turn 34)

Or if you prefer you can calculate your dates in JS, but depending how you do it you may need to format your dates so they will work in your query

Community
  • 1
  • 1
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
-1

Try this :

SELECT age, birthday FROM tablename WHERE age > 22 AND age < 33

I took this in wrong way :

i think here is correct :

SELECT *, TIMESTAMPDIFF(YEAR,birthday,CURDATE()) as age FROM student  WHERE TIMESTAMPDIFF(YEAR,created,CURDATE()) > 22 AND  TIMESTAMPDIFF(YEAR,birthday,CURDATE()) < 33
Monty
  • 1,110
  • 7
  • 15