向 MySQL 表添加一列,该列是文本和另一个自动增量列的值串联的结果?

mysqlmysqli database更新于 2025/9/29 18:20:17

为此,您可以使用 LAST_INSERT_ID()。让我们首先创建一个表 −

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 插入命令在表中插入一些记录 −

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

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

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

以下是向 MySQL 表添加列的查询,该列是连接的结果 −

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

让我们再次检查表记录 −

mysql> select *from DemoTable;

输出

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


相关文章


有用资源