MySQL 8: RANK函数在UPDATE查询中不可能?

MySQL 8 : RANK function in UPDATE query impossible?

我有一张table'photos',每张照片都有一个等级,满分十:

-- ID -- fileName -- grade -- last_rank_computed
   1     fn.jpg      6        NULL
   2     fn2.jpg     1        NULL
   3     fn3.jpg     2.5      NULL
   4     fn4.jpg     NULL     NULL

我需要通过计算所有照片的等级排名来填充 last_rank_computed 字段(其中等级!= null)。结果将是:

-- ID -- fileName -- grade -- last_rank_computed
   1     fn.jpg      6        1
   2     fn2.jpg     1        3
   3     fn3.jpg     2.5      2
   4     fn4.jpg     NULL     NULL

我试过这个查询:

update photos 
set last_rank_computed = RANK() OVER ( ORDER BY grade desc )  
where grade_avg is not null 

但是 MySQL 说:

You cannot use the window function 'rank' in this context.

我可以直接在 PHP 中获取所有行及其各自的等级(因为它在 SELECT 查询中有效),并执行 N UPDATE 查询,但我想这会很糟糕为了表现。如果我要处理 50000 张照片,就性能(时间和内存)而言,MySQL 可能更有效,但如果我错了请告诉我。

您可以通过自连接到计算列来完成此操作:

update photos p
inner join (
  select *,
    rank() over (order by grade desc) as rn
  from photos
  where grade is not null
) pp on pp.id = p.id
set p.last_rank_computed = pp.rn;

参见demo
结果:

| id  | filename | grade | last_rank_computed |
| --- | -------- | ----- | ------------------ |
| 1   | fn.jpg   | 6     | 1                  |
| 2   | fn2.jpg  | 1     | 3                  |
| 3   | fn3.jpg  | 2.5   | 2                  |
| 4   | fn4.jpg  |       |                    |