row_number 更新,mysql 过度分区(备选)

Update on row_number, over partitioned (alternative) in mysql

我有一个 table mmdocpositions,我可以在其中放置文档和位置。位置已被打破,现在每个文档中都有值 2。应该是Document1 1, Document1 2, Document1 3, Document2 1, Document2 2, etc...但是现在是Document1 2, Document1 2, Document1 2, etc...

我已经成功编写了 SQL 脚本来选择正确的结果:

set @row_number := 0;
SELECT *
from
(SELECT 
    @row_number:=CASE
        WHEN @document_nr = document 
            THEN @row_number + 1
        ELSE 1
    END AS num,
    @document_nr:=document
FROM
    mmdocpositions WHERE document IN (SELECT document FROM mmdocpositions where POSITION='2'  GROUP BY document,POSITION having COUNT(*)>1) ORDER BY document)x
num @document_nr:=document
1 CE21100044
2 CE21100044
3 CE21100044
4 CE21100044
1 CE21100046
2 CE21100046
3 CE21100046
4 CE21100046
5 CE21100046
6 CE21100046
1 DA21100419
2 DA21100419
3 DA21100419
4 DA21100419
1 DA21100422
2 DA21100422
3 DA21100422
4 DA21100422
5 DA21100422
6 DA21100422
7 DA21100422
8 DA21100422
9 DA21100422
10 DA21100422
11 DA21100422
12 DA21100422
13 DA21100422
14 DA21100422
15 DA21100422
16 DA21100422
17 DA21100422

我使用了这个解决方法,因为在 MYSQL 版本中没有 row_number 和 OVER BY PARTITION。现在我尝试将其放入 UPDATE 语句中:

    set @row_number := 0;
    UPDATE mmdocpositions SET POSITION=x.num
FROM
    (SELECT 
        @row_number:=CASE
            WHEN @document_nr = document 
                THEN @row_number + 1
            ELSE 1
        END AS num,
        @document_nr:=document
    FROM
        mmdocpositions WHERE document IN (SELECT document FROM mmdocpositions where POSITION='2'  GROUP BY document,POSITION having COUNT(*)>1) ORDER BY document)x
   

我在 HEIDISQL 中遇到 SQL 语法错误。我试图重写代码但无法使其工作。我想知道是否可以这样做,否则我将不得不编写程序。请帮我解决黑客问题!

您的更新命令应如下所示。

你需要加入table然后是新的rownumber

我在 mmdocpositions.id = x.id 加入了两个 table,因为我对你的 table 一无所知,所以你必须改变它以便 mysql 将连接正确的行

set @row_number := 0;
UPDATE mmdocpositions 
INNER JOIN     (SELECT 
    @row_number:=CASE
        WHEN @document_nr = document 
            THEN @row_number + 1
        ELSE 1
    END AS num,
    @document_nr:=document
FROM
    mmdocpositions WHERE document IN (SELECT document FROM mmdocpositions where POSITION='2'  GROUP BY document,POSITION having COUNT(*)>1) ORDER BY document)x
    ON mmdocpositions.id = x.id
SET POSITION=x.num