MySQL在3个相同版本的服务器上的行为不同

时间:2019-03-30 09:22:04

标签: mysql

我已经在两个不同的小提琴网站上运行了此查询,这两个网站都设置为使用MySQL 5.6:

SELECT name, rank, position FROM(
  SELECT name, position,
  @rank:= IF(@prev = name, @rank + 1, 1) AS rank,
  @prev:= name

  FROM (SELECT * FROM drivers 
    LEFT JOIN results on drivers.id = results.driver_id 
    JOIN (SELECT @rank := 1) AS init
    ORDER BY name, results.position ASC) AS temp

) AS derived WHERE rank <= 3 ORDER BY name, rank

应该给每个车手排名前三的位置。该查询可在小提琴1上运行,但不适用于小提琴2或生产服务器上,尽管它们全部在MySQL 5.6上运行。

是否缺少我需要的设置?

Fiddle #1 - working

Fiddle #2 - not working

1 个答案:

答案 0 :(得分:1)

您可以使用以下解决方案:

SELECT name, rank, position FROM (
    SELECT name, position,
        @rank:= IF(@prev = name, @rank + 1, 1) AS rank,
        @prev:= name
    FROM (
        SELECT * 
        FROM drivers LEFT JOIN results ON drivers.id = results.driver_id 
            JOIN (SELECT @rank := 1) AS init_rank
            JOIN (SELECT @prev := '') AS init_prev
        ORDER BY name, results.position ASC
    ) AS temp
) AS derived 
WHERE rank <= 3 
ORDER BY name, rank

我也在@prev上添加了JOIN变量的初始化。

不同的演示:


从MySQL 8.0开始,您可以使用内置的RANK窗口函数。因此,您不需要@prev@rank变量:

SELECT name, `rank`, position FROM (
    SELECT name, position, RANK() OVER (PARTITION BY name ORDER BY name, position) AS `rank`
    FROM drivers LEFT JOIN results ON drivers.id = results.driver_id
) AS derived 
WHERE `rank` <= 3 
ORDER BY name, `rank`

demo on dbfiddle.uk