向 MySQL 表新增一列,該列是來自另一個自動增長列的文字和值連線的結果?
為此,可以使用 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)
使用插入命令在表中插入一些記錄 −
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)
廣告