mysql 查询auto_increment_MySQL查询数据表的Auto_Increment(自增id)
1.一般數(shù)據(jù)表的id都是設(shè)置成auto_increment的,所以當(dāng)插入一條記錄后,可以使用下面的命令來(lái)獲取最新插入記錄的id值
select last_insert_id();
注意:1. 必須是在使用Insert語(yǔ)句后,緊接著使用select last_insert_id()才有效,在沒(méi)有使用過(guò)Insert語(yǔ)句的情況下,查詢(xún)返回的結(jié)果為0;
2.如果在同一條Insert語(yǔ)句插入多條記錄,返回的結(jié)果是第一條記錄對(duì)于的id,如
insert into school.student
(name, age) values
('s1', 18),
('s2', 18),
('s3', 28),
('s4', 19),
('s5', 18);
返回的結(jié)果是s1對(duì)于的id號(hào)。
2. 為什么不直接使用 select max(id) from tableName;
因?yàn)?#xff1a;如果手動(dòng)刪除了最新的數(shù)據(jù),使用 max(id)查詢(xún)的結(jié)果是當(dāng)前剩下數(shù)據(jù)中最大的記錄,
而新插入數(shù)據(jù)則不一定從這個(gè)數(shù)字開(kāi)始計(jì)數(shù)
3. 所以為了準(zhǔn)確的獲取下一條插入記錄的id,應(yīng)該查詢(xún)的是auto_increment, 對(duì)應(yīng)的SQL語(yǔ)句如下:
SELECT auto_increment FROM information_schema.tables where table_schema="dbName" and table_name="tableName";
注意:auto_increment?可以通過(guò)?show table status where `name`='tableName'?查詢(xún)得到,所以相當(dāng)于一個(gè)字段了;
auto_increment返回的是下一條插入記錄的id值,而不是當(dāng)前的最大id值
information_schema.tables照寫(xiě)即可,
table_schema="dbName",指的是數(shù)據(jù)庫(kù)的名字,注意要使用雙引號(hào),
table_name="tableName",指的是表的名字,也要使用雙引號(hào)。
總結(jié)
以上是生活随笔為你收集整理的mysql 查询auto_increment_MySQL查询数据表的Auto_Increment(自增id)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 债券逆回购有风险吗
- 下一篇: mysql数据库前端缓存_什么是MySQ