gpt4 book ai didi

MySQL - 基于其他列的订单自动填充列

转载 作者:行者123 更新时间:2023-11-29 18:14:53 25 4
gpt4 key购买 nike

我是一个非常缺乏经验的 SQL 用户。我从来没有真正使用 SQL 来做自动填充列之类的事情。主要是选择(连接等)。

我有一个表,我想将值填充到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;

关于MySQL - 基于其他列的订单自动填充列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com