【问题标题】:Update on row_number, over partitioned (alternative) in mysql更新row_number,在mysql中分区(替代)
【发布时间】:2021-12-31 07:29:34
【问题描述】:

我有一个表格 mmdocpositions 用于放置文档和职位。位置已被破坏,现在每个文档中都有值 2。应该是 Document1 1、Document1 2、Document1 3、Document2 1、Document2 2 等……但现在是 Document1 2、Document1 2、Document1 2 等……

我已经成功编写了选择正确结果的 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 语法错误。我试图重写代码但无法使其工作。我想知道是否可以这样做,或者我将不得不编写程序。请帮我解决黑客!

【问题讨论】:

  • 添加一些样本数据真的会让你明白你的问题的重点。
  • 谢谢,我已经添加了选择结果的图片。
  • 请阅读meta.stackoverflow.com/questions/285551/… 并编辑您的问题以完整填写minimal reproducible example
  • 您在 HEIDISQL 中没有语法错误。您在 SQL 中有语法错误。 UPDATE 语句的语法不正确。 (该声明中没有FROM
  • 我也尝试过不使用 FORM 以及我在网上找到的其他变体。没有运气。这就是为什么我认为你们会帮助我的原因,我在这个问题上得到了减分:)

标签: mysql mariadb


【解决方案1】:

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

你需要加入表格然后是新的行号

我在 mmdocpositions.id = x.id 上加入了两个表,因为我对您的表一无所知,所以您必须更改它以便 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

【讨论】:

  • 你做得非常好!!!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多