MYSQL,将数据从一个表复制到另一个表,并以 varchar 递增 [英] MYSQL, copy data from one table to another table with increment in varchar

查看:56
本文介绍了MYSQL,将数据从一个表复制到另一个表,并以 varchar 递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子

表_1:用户

I have Two tables

Table_1 : users

id name
-------
1  john
2  john2
3  john3

表_2:tbl_account_level

Table_2 : tbl_account_level

ID    Code      Detail
------------------------
1     00001     GPS
2     00002     CAMERA
3     00003     Tracking System

现在,我想通过 mysql 将 users 表中的所有数据复制到 tbl_account_level 中,代码为 Varchar .

我的查询:

  insert into tbl_account_level (code, detail)select cast("00003" as unsigned) + 1, name from users ;

结果有点像,

ID    Code      Detail
------------------------
1     00001     GPS
2     00002     CAMERA
3     00003     Tracking System
4     4         john
5     5         john2
6     6         john3

我想要类似的结果

ID    Code      Detail
------------------------
1     00001     GPS
2     00002     CAMERA
3     00003     Tracking System
4     00004     john
5     00005     john2
6     00006     john3

推荐答案

可以使用lpad在增量后添加前导0

You can use lpad for adding the leading 0 after the increment

insert into tbl_account_level (code, detail)
select lpad(cast(code  as unsigned) + 1, 5 ,'0'), name 
from users

如果您需要行增量,您可以使用 multi 语句作为

and if you need row increment you coudl use a multi statement as

SET @row_number = 0; 
insert into tbl_account_level (code, detail)
select lpad(cast(code  as unsigned) +  @row_number:=@row_number + 1, 4 ,'0'), name 
from users ;

这篇关于MYSQL,将数据从一个表复制到另一个表,并以 varchar 递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆