วิธีดึงค่า Auto Increment สูงสุด (ล่าสุด) ใน MySQL
ใช้ ORDER BY ... DESC LIMIT 1 เพื่อดึงแถวที่มีค่า Auto Increment มากที่สุด
SELECT * FROM yourTableName ORDER BY autoIncrementColumn DESC LIMIT 1;
ตัวอย่างการใช้งาน
สร้างตารางมี UserId เป็น Auto Increment:
mysql> create table DemoTable (
UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserName varchar(20)
);
mysql> insert into DemoTable(UserName) values('John');
mysql> insert into DemoTable(UserName) values('Larry');
mysql> insert into DemoTable(UserName) values('Chris');
mysql> insert into DemoTable(UserName) values('Bob');
mysql> insert into DemoTable(UserName) values('Carol');
mysql> insert into DemoTable(UserName) values('David');
mysql> insert into DemoTable(UserName) values('Robert');
ข้อมูลทั้งหมด:
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Larry | | 3 | Chris | | 4 | Bob | | 5 | Carol | | 6 | David | | 7 | Robert | +--------+----------+
คิวรีหา Auto Increment สูงสุด:
mysql> select * from DemoTable order by UserId desc limit 0,1;
+--------+----------+ | UserId | UserName | +--------+----------+ | 7 | Robert | +--------+----------+
วิธีอื่นๆ:
SELECT MAX(UserId) FROM DemoTable;- เร็วกว่า ถ้ามี Index (PK มี Index อัตโนมัติ)SELECT LAST_INSERT_ID();- คืนค่า Auto Increment ของ INSERT ล่าสุดใน Session นี้เท่านั้น (ไม่ใช่ค่าสูงสุดในตาราง)SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='DemoTable';- ค่าถัดไปที่จะใช้ (ไม่ใช่ค่าสูงสุดที่มีอยู่)
แนะนำ: ใช้ MAX(UserId) สำหรับหาค่าสูงสุดที่มีอยู่ | ใช้ LAST_INSERT_ID() สำหรับดึง ID ที่เพิ่ง INSERT ไป