I have a user table with the user’s birthday (YYYY-MM-DD) as well as age. I want to run a script to calculate and update the age column nightly via cron.
This SQL works well for selecting and calculating the age:
SELECT
DATE_FORMAT(NOW(), '%Y') -
DATE_FORMAT(`birthday`, '%Y') -
(DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(`birthday`, '00-%m-%d')) AS age
FROM
`jos_jcourse_students`
But is it possible to update the age column with a single statement? Tried the following, but all I managed to do was populate the age column with all 0s! Do I need to use some sort of MySQL loop?
UPDATE
`jos_jcourse_students`
SET
age = "SELECT DATE_FORMAT(NOW(), '%Y') -
DATE_FORMAT(`birthday`, '%Y') -
(DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(`birthday`, '00-%m-%d')) AS age
FROM
`jos_jcourse_students`"
OR according to your logic it will be