【发布时间】: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 语法错误。我试图重写代码但无法使其工作。我想知道是否可以这样做,或者我将不得不编写程序。请帮我解决黑客!
【问题讨论】:
-
添加一些样本数据真的会让你明白你的问题的重点。
-
谢谢,我已经添加了选择结果的图片。
-
您在 HEIDISQL 中没有语法错误。您在 SQL 中有语法错误。 UPDATE 语句的语法不正确。 (该声明中没有
FROM) -
我也尝试过不使用 FORM 以及我在网上找到的其他变体。没有运气。这就是为什么我认为你们会帮助我的原因,我在这个问题上得到了减分:)