Mysql用group by更新最大值

时间:2013-10-16 10:33:17

标签: mysql sql group-by sql-update

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

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列?

我尝试使用内部联接,但失败了:

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

1 个答案:

答案 0 :(得分:8)

您可以使用此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

请参阅小提琴here