2

I will like to understand the most efficient way to achieve this:

I have a MySQL table with my users info, including birthday (YYYY/MM/DD). My objective is to retrieve an array (php) with the total of user for each individual age from 10 to 60 years old. I can just query all my users, pass the birthday to a birthday to age php function I wrote and then populate an array with the totals. But I wonder if there's a way to build an sql query that does this job for me?

DomingoSL
  • 14,920
  • 24
  • 99
  • 173

3 Answers3

2

You should be able to group the rows:

SELECT
    FLOOR(DATEDIFF(NOW(), `birthday`)/365) AS 'Age',
    COUNT(*)
FROM `users`
WHERE FLOOR(DATEDIFF(NOW(), `birthday`)/365) BETWEEN 10 AND 60
AND `id` IN (1, 3, 5, 12, 29)
GROUP BY FLOOR(DATEDIFF(NOW(), `birthday`)/365)
ORDER BY FLOOR(DATEDIFF(NOW(), `birthday`)/365) ASC

The result won't contain ages that have no users, but I'm not sure why you'd need that.

Updates - Added an id filter - Fixed the date calculation (oops!) - Named the new column

Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
0
SELECT * FROM tableName 
         WHERE dateOfBirth >= (CURRENT_DATE - INTERVAL 60 YEAR)   
         AND dateOfBirth <= ( CURRENT_DATE - INTERVAL 10 YEAR )

Hopefully I don't get slammed by the database experts on this one...

Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
-1

You will need to use MySql's DATEDIFF().

SELECT USER, DATEOFBIRTH FROM USERTABLE WHERE DATEDIFF(DATEOFBIRTH,NOW()) < 60;
WhoaItsAFactorial
  • 3,538
  • 4
  • 28
  • 45