我有3个表如下:
+-----------+--------------+------+-----+---------+-------+
| 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 | |
+-------+--------------+------+-----+---------+-------+
我试图找出哪个演员在电影之间的时间最长。
在参与者相同的情况下(或者默认为 0),我正在尝试使用局部变量来引用前一行的值。但是由于某种原因,@previousName 变量会返回一个随机的名称列表。
这是代码:
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;
这是我得到 的:结果表的图片
注意我使用的是 mySQL V5.7,所以窗口函数不是一个选项。