You can do this with a UPDATE statement. (But, do you really want to?)
First, write the SELECT
statement that would give you the result.
SELECT g.player_id
, g.tournament_id
, p.birthday
, t.tournament_date
, DATEDIFF(t.tournament_date,p.birthday) AS days_diff
FROM games g
JOIN player p ON p.id = g.player_id
JOIN tournament t ON t.id = g.tournament_id
Just add an expression that does the calculation you want to perform, and return that as a column.
Then, you can use that SELECT statement as an inline view in an UPDATE statement. Assuming you've added a age_in_days
column to the games
table
UPDATE games d
JOIN (
SELECT g.player_id
, g.tournament_id
, p.birthday
, t.tournament_date
, DATEDIFF(t.tournament_date,p.birthday) AS days_diff
FROM games g
JOIN player p ON p.id = g.player_id
JOIN tournament t ON t.id = g.tournament_id
) s
ON s.player_id = d.player_id
AND s.tournament_id = d.tournament_id
SET s.age_in_days = s.days_diff
Next, we have to be concerned about "large" tables, and avoiding a huge transaction that generates a boatload of rollback (if these are InnoDB tables).
If that's a concern, do the UPDATE operation in "batches" by breaking it up, by adding a predicate in the inline view query, for example, WHERE g.player_id = 42
, and running that same UPDATE, once for each player_id
.
If you want age in "decimal years", you'd need to develop an expression to return that. (As a rudimentary approximation, divide the difference in days by the number of days in a year 365.25
. That would get you pretty close.)
(At the beginning of my answer, I asked, do you really want to.
Beware that if a player birthday
value is updated, or a tournament_date
is changed, the calculated values stored in the games
table will be inconsistent.