首页 > 解决方案 > MySQL 以增量方式更新列

问题描述

I have MySQL table column as follows :

+------------+
|  auto_no   |
+------------+
| 2020-12750 |
| 2020-12751 |
| 2020-12752 |
| 2020-12753 |
| 2020-12754 |
+------------+

然后我需要使用从 00001 开始的 LIKE% 格式以增量方式更新此列,如下所示:

+------------+
|  auto_no   |
+------------+
| 2020-00001 |
| 2020-00002 |
| 2020-00003 |
| 2020-00004 |
| 2020-00005 |
+------------+

我尝试了以下方法:

update letter set auto_no = auto_no + auto_no LIKE %2020-%

但我认为,这不是正确的方法。可用于循环。如何更改我的查询?任何人都可以帮忙吗?

标签: mysql

解决方案


将表连接到一个查询,该查询计算auto_nos 小于或等于 eachauto_no并更新:

update letter l inner join (
  select t.auto_no, 
    (select count(*) from letter where auto_no like '2020-%' and auto_no <= t.auto_no) counter
  from letter t
  where auto_no like '2020-%'
) t on t.auto_no = l.auto_no
set l.auto_no = concat(left(l.auto_no, 5), lpad(t.counter, 5, '0'));

请参阅演示
或者如果 s 之间没有间隙,则另一种选择auto_no

update letter l cross join (
  select right(min(auto_no), 5) start_from
  from letter 
  where auto_no like '2020-%'
) t 
set l.auto_no = concat(left(l.auto_no, 5), lpad(right(l.auto_no, 5) - t.start_from + 1, 5, '0'))
where l.auto_no like '2020-%';   

请参阅演示
结果:

| auto_no    |
| ---------- |
| 2020-00001 |
| 2020-00002 |
| 2020-00003 |
| 2020-00004 |
| 2020-00005 |

推荐阅读