简体   繁体   中英

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

 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. 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. If you're using sql_mode=PIPES_AS_CONCAT (or equivalent ), then:

insert into table1 (username) 
select prefix || (LPAD(Coalesce(MAX(id),0) + 1,3, '0'))
from table1;

otherwise use CONCAT .

Problems:

  1. As Matt mentioned you need to use CONCAT() in MySql
  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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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