将选择查询转换为更新查询 - 每组编号行数

时间:2015-03-05 00:17:37

标签: mysql sql-update

我有一个select查询,它附加一列顺序/增量编号,对Album中的每次更改重新开始。它基于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

2 个答案:

答案 0 :(得分:2)

此查询将执行您想要的操作(使用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或类似的东西来修复顺序(如果是这样,它应该添加到派生表的末尾)。< / p>

示例输出:

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

答案 1 :(得分:0)

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

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