且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-08 22:49:03

问题:

  1. 如Matt所述,您需要在MySql中使用CONCAT()
  2. 对于插入的第一条记录,SELECT返回NULL,因此您需要使用COALESCE()IFNULL()来获取默认值以进行串联
  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

您的查询应如下所示

INSERT INTO table1 (username)
SELECT CONCAT(COALESCE(prefix, 'AB'), LPAD(COALESCE(MAX(id), 0) + 1, 3, '0'))
  FROM table1

结果:


| ID | PREFIX | USERNAME |
--------------------------
|  1 |     AB |    AB001 |
|  2 |     AB |    AB002 |

这里是 SQLFddle

Here is SQLFddle