4

我有一个已经有很多行的简单表:

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
4

1 回答 1

9

您可以使用此 SELECT 查询,该查询将返回relative_order您需要的:

SELECT
  t1.id,
  t1.grade,
  COUNT(t2.id) relative_order
FROM
  yourtable t1 INNER JOIN yourtable t2
  ON t1.grade=t2.grade AND t1.id>=t2.id
GROUP BY
  t1.id,
  t1.grade

或者,如果您想更新该值,您可以将您的表与之前的查询连接起来,如下所示:

UPDATE
  yourtable INNER JOIN (
    SELECT
      t1.id,
      t1.grade,
      COUNT(t2.id) relative_order
    FROM
      yourtable t1 INNER JOIN yourtable t2
      ON t1.grade=t2.grade AND t1.id>=t2.id
    GROUP BY
      t1.id,
      t1.grade) seq
  ON yourtable.id=seq.id AND yourtable.grade=seq.grade
SET
  yourtable.relative_order = seq.relative_order

在此处查看小提琴。

于 2013-10-16T10:44:18.637 回答