我有一个已经有很多行的简单表:
id grade ...
1 1 ...
2 2 ...
3 2 ...
4 1 ...
5 1 ...
现在我想添加一个列"relative_order"
,这是那个年级的顺序。所以表格变成:
id grade ... relative_order 1 1 ... 1 2 2 ... 1 3 2 ... 2 4 1 ... 2 5 1 ... 3
添加列后,所有 relative_order 首先变为 0。如何使用update
语法填充 relative_order 列?
我尝试使用inner join,但失败了:
UPDATE table AS i
INNER JOIN(
SELECT max(relative_order) as mOrder,grade
FROM table
GROUP BY grade
) AS j
ON i.grade = j.grade
SET i.relative_order = j.mOrder + 1