Add a column to a MySQL table which is the result of concatenation of text and value from another auto increment column?

MySQLMySQLi Database

For this, you can use LAST_INSERT_ID(). Let us first create a table −

mysql> create table DemoTable
   (
   UserId int(6) unsigned zerofill NOT NULL AUTO_INCREMENT,
   UserAutoIncrement char(100) default null,
   PRIMARY KEY(UserId)
   );
Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------+-------------------+
| UserId | UserAutoIncrement |
+--------+-------------------+
| 000001 | NULL              |
+--------+-------------------+
1 row in set (0.00 sec)

Following is the query to add a column to a MySQL table which is the result of concatenation −

mysql> update DemoTable set UserAutoIncrement=CONCAT('USER-', UserId) WHERE UserId = LAST_INSERT_ID();
Query OK, 1 row affected (0.20 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

Output

+--------+-------------------+
| UserId | UserAutoIncrement |
+--------+-------------------+
| 000001 | USER-000001       |
+--------+-------------------+
1 row in set (0.00 sec)
raja
Published on 20-Aug-2019 09:09:39
Advertisements