如何批量更新表

本文关键字:更新 何批量 | 更新日期: 2023-09-27 18:34:36

假设,我有一个看起来像这样的表:

+----+-----------+------+-------+--+
| id | Part      | Seq  | Model |  |
+----+-----------+------+-------+--+
| 1  | Head      | 0    | 3     |  |
| 2  | Neck      | 1    | 3     |  |
| 3  | Shoulders | 11   | 3     |  |
| 4  | Groin     | 2    | 3     |  |
| 5  | Stomach   | 5    | 3     |  |
+----+-----------+------+-------+--+

如您所见,Seq 字段是这些项目在前端的显示顺序。这是序列 0, 1, 2, 5, 11。现在,用户想要对列表重新排序。如果他们希望 Stomach (id: 5( 有seq: 0我将如何编写查询来仅更新模型 3 的所有 Seq 值?

如何批量更新表

这里有一种方法将序列号重新分配为有序整数,首先是"Stomach":

with toupdate as (
      select t.*,
             row_number() over (partition by model -- not really necessary
                                order by (case when Part = 'Stomach' then -1
                                               else seq
                                          end)
                               ) as newseq
      from t
      where model = 3
     )
update toupdate
    set seq = newseq;