简体   繁体   English

通过从两列中选择值来插入同一表中的一列

[英]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;

otherwise use CONCAT . 否则使用CONCAT

Problems: 问题:

  1. As Matt mentioned you need to use CONCAT() in MySql 正如Matt所述,您需要在MySql中使用CONCAT()
  2. For the first record being inserted your SELECT returns NULL therefore you need to use COALESCE() or IFNULL() to get DEFAULT value for concatenation 对于插入的第一条记录,SELECT返回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 |

Here is SQLFddle 这是SQLFddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM