Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เพิ่มคอลัมน์ที่เป็นผลรวมของข้อความและค่า Auto Increment ใน 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)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;

ผลลัพธ์

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

คำสั่งอัปเดตคอลัมน์เป็นการต่อข้อความกับ Auto Increment

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)

คำอธิบาย: LAST_INSERT_ID() คืนค่า AUTO_INCREMENT ล่าสุด CONCAT('USER-', UserId) รวมข้อความกับค่า ID (รูปแบบ zerofill 6 หลัก)