MySQL 獲取最新插入資料的id

2021-09-17 18:45:47 字數 441 閱讀 3798

select @@identity;

@@identity 返回為跨所有作用域的當前會話中的某個表生成的最新標識值。

插入資料之後,不管是再執行什麼操作(除了插入資料之後的更新、查詢、刪除等),只用該方法查詢到的id,都是最後插入資料對應的id。

例如:插入一條id為10,name為」李四「的資料,之後不管是再執行什麼操作(除了插入資料之後的更新、查詢、刪除等),使用select @@identity; 查詢到的id都是10;

select last_insert_id();

select last_insert_id();:得到剛 insert 進去記錄的主鍵值,只適用與自增主鍵。(這點還沒有證明)

和第一種方法一樣,不受除插入操作之外的操作影響。

擴充套件之處:

mysql插入資料,獲取最新插入的ID(自增列)

在mysql中,使用auto increment型別的id欄位作為表的主鍵。通常的做法,是通過 select max id from tablename 的做法,但是顯然這種做法需要考慮併發的情況,需要在事務中對主表以 x鎖 待獲得max id 的值以後,再解鎖。這種做法需要的步驟比較多,有些麻煩,...

Oracle獲取最新插入的字段值

declare newmas id number begin insert into mu alarm strategy mas id,mas name,mas insert time,mas update time,mas user id values 0,testtt to date 2013 ...

SQL獲取表中最新插入的記錄

對於想要得到乙個表中的最後乙個插入操作所產生的id的最好用ident current tbname insert into table field1,field2,values field1value field2value select ident current recordid asnewid...