我正在尝试对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和0阶的行上。到目前为止,我尝试选择要在子查询中更新的值,并使用max()+ 1更新行
…不幸的是,由于选择不允许与更新在同一表上使用,因此无法使用。有没有办法做到这一点?
尝试这种方式:
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` ;
演示-> http://www.sqlfiddle.com/#!2/6f2102/1