MySQL - 根据其他列自动填充订单列

MySQL - autofill column for order based on other columns

我是一个没有经验的 SQL 用户。我从来没有真正使用 SQL 来进行自动填充列之类的事情。主要是 SELECTS(JOINS 等)。

我有一个 table,我想将值填充到 article_order 列中,以便为每个 id_issue 排序 id_article。

我在 sql fiddle

上有这个例子
+------------------------+----------+------------+---------------+
| id_issue_article_issue | id_issue | id_article | article_order |
+------------------------+----------+------------+---------------+
|                      1 |        1 |          1 | NULL          |
|                      2 |        1 |          2 | NULL          |
|                      3 |        2 |          3 | NULL          |
|                      4 |        2 |          4 | NULL          |
|                      5 |        2 |          5 | NULL          |
+------------------------+----------+------------+---------------+
Desired table
+------------------------+----------+------------+---------------+
| id_issue_article_issue | id_issue | id_article | article_order |
+------------------------+----------+------------+---------------+
|                      1 |        1 |          1 |             1 |
|                      2 |        1 |          2 |             2 |
|                      3 |        2 |          3 |             1 |
|                      4 |        2 |          4 |             2 |
|                      5 |        2 |          5 |             3 |
+------------------------+----------+------------+---------------+

我一直在寻找解决方案,我可能错过了一些东西,但我还是想不通。 即使是提示也会有所帮助。 提前致谢!

这在 MySQL 中有点棘手,但您可以使用变量来完成:

set @rn := 0;
set @ai := -1;

update t
    set article_order = if(@ai = id_issue, @rn := @rn + 1,
                           if(@ai := id_issue, @rn := 1, @rn := 1
                             )
                          )
    order by id_issue, id_article;