Retrieve database records by date field?

Asked

Viewed 239 times

1

How do I recover users recorded in a database table by the dt_birth field through two values representing the minimum and maximum age of the users that will be returned, the minimum and maximum age does not always come together can-if you specify only the minimum age, or only the maximum age. Is subquery necessary? Note: the database is mysql.

Basically this would be the query (where 18 and 30 are the age limits) the date of birth this in the American format YYYY/MM/DD the Where clause is just an example, it does not work.

SELECT nome, dt_nascimento FROM usuario WHERE dt_nascimento > 18 AND dt_nascimento < 30;
  • You can put an example of the table structure and what result you want to get?

2 answers

3

From what I understand you can just do the following:

select nome, dt_nascimento 
from tbl_tabela1
where TIMESTAMPDIFF(YEAR, dt_nascimento , CURDATE()) between 18 and 30

I am assuming that the date is stored in the database in the appropriate format. If not, you can always convert (CAST) to date or datetime.

TIMESTAMPDIFF can also return the difference between two dates in DAYS or MONTHS, just replace YEAR by MONTH or DAY

  • Does not take into account the month and day of birth, only the year.

  • @ramaral, the test I made select timestampdiff(YEAR, '1994-04-15', '2015-04-14') returns 20 -- select timestampdiff(YEAR, '1994-04-15', '2015-04-16') returns 21 so I think it’s working correctly

  • I’m sorry, I was wrong. (+1)

  • No problem. After your comment I was also in doubt whether it produced the correct result or not. :)

2


Add 18 years and 30 years to date of birth and compare to current date .

SELECT nome, dt_nascimento 
FROM tbl_tabela1 
WHERE DATE_ADD(dt_nascimento,INTERVAL 18 YEAR) <= CURDATE()
AND DATE_ADD(dt_nascimento,INTERVAL 30 YEAR) >= CURDATE();  

If dt_birth + 18 years is <= the current date is because you are over 18 years old.
If dt_birth + 30 years is >= the current date is because it is less than 30 years old.

  • ,@extension, the operators (<= and >=) are correct same?

  • Yes. Example for those aged 52: 1962 + 18 = 1980 <= 2015 yes ,is over 18 years old; 1962 + 30 = 1992 >= 2015 no, is over 30 years old.

  • ,@ramaral, this Where clause is also valid in PDO (PHP Data Object)

  • I don’t know PHP, but I think so.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.