我想在mysql表上进行更新:
PrimaryId | SecondaryId | Order
-----------+-------------+-------
1 | 1 | 0
2 | 1 | 0
3 | 2 | 0
4 | 3 | 0
5 | 3 | 0
6 | 3 | 0
为:
PrimaryId | SecondaryId | Order
-----------+-------------+-------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 3 | 1
5 | 3 | 2
6 | 3 | 3
在具有相同辅助ID和Order 0的行上。 到目前为止,我试图选择要在子查询中更新的值,并使用max()+ 1更新行
...遗憾的是,这不起作用,因为不允许select与更新在同一个表上工作。有没有办法做到这一点?
答案 0 :(得分:2)
尝试这种方式:
UPDATE Table1 t1
JOIN (
SELECT `PrimaryId`,
`SecondaryId`,
(SELECT count(*)
FROM Table1 t1
WHERE t1.`SecondaryId` = t.`SecondaryId`
AND t1.`PrimaryId` <= t.`PrimaryId`
) `Order`
FROM Table1 t
) t2
ON t1.`PrimaryId` = t2.`PrimaryId`
SET t1.`Order` = t2.`Order`
;
演示 - &gt; http://www.sqlfiddle.com/#!2/6f2102/1