将 select 查询转换为更新查询 - 每组编号行

Converting a select query to an update query - Numbering Rows Per Group

我有一个 select 查询,它附加了一个 sequential/incremental 编号列,在 Album 中每次更改都从 1 重新开始。它基于 this tutorial

set @vAlbum = '';
set @vnum  = 1;

SELECT 
    Song,
    Album,
    @vnum:=IF(@vAlbum = Album, @vnum + 1, 1) AS row_number,
    @vAlbum:=Album AS dummy
FROM
    tablename

如何将其修改为更新查询,而不是创建列 row_number,而是更新列 TrackNum

期望的结果:

Album|Song|TrackNum
Hits1|AAAA|1
Hits1|BBBB|2
Hits1|CCCC|3
Hits2|AAAA|1
Hits2|BBBB|2
Hits3|AAAA|1
Hits3|BBBB|2
Hits3|CCCC|3
Hits3|DDDD|4

只需执行下面的 UPDATE 查询即可实现您的目标。并确保通过添加 WHERE 子句来指定要更新的行。见下文:

SELECT @i := 0;
UPDATE tablename SET TrackNum= (SELECT @i := @i + 1) 
WHERE Album = 'Hits1';

此查询将执行您想要的操作(使用 MySQL 5.6.17 测试):

SET @Album = '';
SET @num  = 1;

UPDATE tablename t,
    (SELECT 
        Song,
        Album,
        @num := IF(@Album = Album, @num + 1, 1) AS row_number,
        @Album := Album AS dummy
    FROM
        tablename) t2 
SET 
    t.TrackNum = t2.row_number
WHERE
    t.album = t2.album AND t.song = t2.song;

请注意,歌曲的编号顺序可能是随机的,也许您想添加一个 ORDER BY Album, Song ASC 或类似的东西来固定顺序(如果是这样,它应该添加到派生的 table).

示例输出:

Album   Song  TrackNum
Hits1   AAAA    1
Hits1   BBBB    2
Hits1   CCCC    3
Hits2   AAAA    1
Hits2   BBBB    2
Hits3   AAAA    1
Hits3   BBBB    2
Hits3   CCCC    3
Hits3   DDDD    4