mysql - 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-%
但我认为,这不是正确的方法。可用于循环。如何更改我的查询?任何人都可以帮忙吗?
解决方案
将表连接到一个查询,该查询计算auto_no
s 小于或等于 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 |
推荐阅读
- jira - Jira 中后功能的执行顺序看起来不正确
- xml-parsing - publicId 和 systemId 之间需要空格,但 XML 看起来没问题
- python-3.x - 如何以异步方式执行 ZeroMQ PUSH/PULL 原型?
- python - bittorrent 对等线下载元数据,bdecode 失败
- laravel - fetch-blob-not post image not wroking with Laravel api - 反应原生
- spring-security - 处理 org.jasig.cas.client.validation.TicketValidationException
- linux - 如何使用 gdk 和 Rust 获取当前活动窗口的标题?
- docker - 如何从 Docker 为 jenkins 生成 API 令牌
- javascript - setSinkId 仅适用于
- python - 气流:无法访问 AWS 提供商