[英]insert by selecting values from two columns into a column from the same table
Please I am inserting values by selecting two values from two columns into one column in the same table.Below are my queries. 请通过从两列中选择两个值到同一表的一列中来插入值。以下是我的查询。
create table table1(
id int(3) zerofill auto_increment primary key,
prefix varchar(10) default "AB",
username varchar(10)
)
engine=innodb;
Mysql insert query MySQL插入查询
insert into table1 (username)
select prefix + (LPAD(Coalesce(MAX(id),0) + 1,3, '0'))
from table1;
The above insert query does not work,it gives null in the username column,please any help is appreciated.Thanks. 上面的插入查询不起作用,它在用户名列中提供了null,请提供任何帮助。谢谢。 The expected results is below.
预期结果如下。
id Prefix username
001 AB AB001
002 AB AB002
003 AB AB003
+
is not the string concatenation operator in MySQL. +
不是MySQL中的字符串连接运算符。 If you're using sql_mode=PIPES_AS_CONCAT
(or equivalent ), then: 如果您使用的是
sql_mode=PIPES_AS_CONCAT
(或等效的 ),则:
insert into table1 (username)
select prefix || (LPAD(Coalesce(MAX(id),0) + 1,3, '0'))
from table1;
Problems: 问题:
CONCAT()
in MySql CONCAT()
NULL
therefore you need to use COALESCE()
or IFNULL()
to get DEFAULT value for concatenation NULL
因此您需要使用COALESCE()
或IFNULL()
来获取DEFAULT值以进行串联 Your query should look like this 您的查询应如下所示
INSERT INTO table1 (username)
SELECT CONCAT(COALESCE(prefix, 'AB'), LPAD(COALESCE(MAX(id), 0) + 1, 3, '0'))
FROM table1
Outcome: 结果:
| ID | PREFIX | USERNAME | -------------------------- | 1 | AB | AB001 | | 2 | AB | AB002 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.