我有一個表格 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
| 數量 | @document_nr:=檔案 |
|---|---|
| 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 語法錯誤。我試圖重寫代碼,但無法使其作業。我想知道是否可以這樣做,否則我將不得不撰寫程式。請幫我解決黑客!
uj5u.com熱心網友回復:
您的更新命令應如下所示。
你需要加入表然后新的行號
我在 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362092.html
上一篇:分組依據在SQL查詢中創建的類別
