I have 3 tables as follows:
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| full_name | varchar(200) | YES | | NULL | |
| gender | varchar(1) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| actor_id | int(11) | YES | MUL | NULL | |
| movie_id | int(11) | YES | MUL | NULL | |
| salary | int(11) | YES | | NULL | |
+----------+---------+------+-----+---------+-------+
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| title | varchar(100) | YES | | NULL | |
| year | int(11) | YES | | NULL | |
| genre | varchar(100) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
I'm trying to figure out which actor has the longest time between movies.
I'm trying to use local variables to reference the previous row value in the case where the actor was the same (or else it defaults to 0). However for some reason the @previousName variable returns a random list of names.
Here is the code:
SELECT
a.full_name,
m.year,
m.title,
@PreviousName,
@PreviousYear,
if(@PreviousName = a.full_name, m.year - @PreviousYear, 0) AS Delta,
@PreviousName := a.full_name,
@PreviousYear := m.year
FROM
actors AS a
INNER JOIN
cast AS c ON a.id = c.actor_id
INNER JOIN
movies AS m ON c.movie_id = m.id,
(SELECT @PreviousName := null, @PreviousYear := 999) as SQLVars
ORDER BY full_name;
And here is what I get: Picture of result table
Note I am using mySQL V5.7 so window functions are not an option.