วิธีที่ 1: SHOW TABLE STATUS (แนะนำ)
รูปแบบคำสั่ง
SHOW TABLE STATUS LIKE 'yourTableName'\G
วิธีที่ 2: Query FROM INFORMATION_SCHEMA
รูปแบบคำสั่ง
SELECT `AUTO_INCREMENT` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = 'yourDatabaseName' AND `TABLE_NAME` = 'yourTableName';
ตัวอย่างครบถ้วน
1. สร้างตารางและเพิ่มข้อมูล 7 แถว
mysql> create table viewAutoIncrementDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(20)
-> );
Query OK, 0 rows affected (0.59 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('Sam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('David');
Query OK, 1 row affected (0.16 sec)
mysql> insert into viewAutoIncrementDemo(UserName) values('Larry');
Query OK, 1 row affected (0.11 sec)
2. ดูข้อมูล
mysql> select * from viewAutoIncrementDemo;
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | | 5 | Mike | | 6 | David | | 7 | Larry | +--------+----------+
3. วิธีที่ 1: SHOW TABLE STATUS
mysql> SHOW TABLE STATUS LIKE 'viewAutoIncrementDemo'\G
*************************** 1. row ***************************
Name: viewautoincrementdemo
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 7
Avg_row_length: 2340
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 8
Create_time: 2019-03-02 04:05:20
Update_time: 2019-03-02 04:06:11
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.08 sec)
ดูที่ Auto_increment: 8 = ค่าถัดไปที่จะใช้
4. วิธีที่ 2: INFORMATION_SCHEMA
mysql> SELECT `AUTO_INCREMENT`
-> FROM `information_schema`.`TABLES`
-> WHERE `TABLE_SCHEMA` = 'sample'
-> AND `TABLE_NAME` = 'viewAutoIncrementDemo';
+----------------+ | AUTO_INCREMENT | +----------------+ | 8 | +----------------+
ข้อแตกต่าง
| วิธี | ข้อดี | ข้อจำกัด |
|---|---|---|
| SHOW TABLE STATUS | เห็นข้อมูลครบ (engine, rows, size, collation) | ต้องรู้ table name แน่นอน |
| INFORMATION_SCHEMA | query ได้หลายตารางพร้อมกัน, ใช้ใน subquery ได้ | ต้องระบุ database name |
รีเซ็ต AUTO_INCREMENT
ALTER TABLE table_name AUTO_INCREMENT = 1;
(ต้องใช้หลัง TRUNCATE หรือ DELETE ทั้งตาราง)