Mysql自增字段

2022-09-18 09:57:20 字數 1351 閱讀 4021

1.關鍵字 

auto_increment

2.自增用法 

例: create table animals ( id mediumint not null auto_increment, 

name char(30) not null, 

primary key (id));

3.關於自增

q:怎麼獲得當前的自增的最大值?

q:怎麼獲得table的當前自增最大值? 

a:select @@identity

a:select max(id) from table

q:對自增的理解? 

a: 一般情況下獲取剛插入的資料的id,使用select max(id) from table 是可以的。last_insert_id 是與table無關的,如果向表a插入資料後,再向表b插入資料,last_insert_id會改變。

使用單insert語句插入多條記錄, last_insert_id返回乙個列表。

@@identity是表示的是最近一次向具有identity屬性(即自增列)的表插入資料時對應的自增列的值,是系統定義的全域性變數。比如有個表a,它的自增列是id,當向a表插入一行資料後,如果插入資料後自增列的值自動增加至101,則通過select@@identity得到的值就是101。

注:last_insert_id是乙個函式.

用法:last_insert_id()

q:mysql中的last_insert_id()和mssql中的@@identity 

a:按照應用需要,常常要取得剛剛插入資料庫表裡的記錄的id值。 

在mysql中可以使用last_insert_id()函式,在mssql中使用@@identity。挺方便的乙個函式。

但是,這裡需要注意的是,當使用insert語句插入多條記錄的時候,使用last_insert_id()返回的還是第一條的id值,而@@identity返回最後一條。

q:mysql_insert_id()與last_insert_id()

a:mysql_insert_id() 將 mysql 內部的 c api 函式 mysql_insert_id() 的返回值轉換成 long(php中命名為int)。如果 auto_increment 的列的型別是 bigint,則 mysql_insert_id() 返回的值將不正確。可以在 sql查詢中用 mysql 內部的 sql 函式 last_insert_id() 來替代。

mysql的last_insert_id()的介紹 mysql_insert_id()就是呼叫last_insert_id()來實現的。

在mysql中用last_insert_id()....在程式中用mysql_insert_id(). 

**:

mysql 自增字段原理 MySQL自增字段暴增

找了點資料 從網上看到一篇文章,mysql在檢測到表中有損壞的記錄時,會自動修復,為了保證資料的完整性,mysql會以空格 0x20 寫進磁碟來完成修復。根據欄位的型別,自增字段的長度不同,所允許的最大值也不同。見下 int 10 unsigned型別最大值十進位制為4294967295,十六進製制...

mysql自增字段重排

由於刪除了某些記錄行,所以自增字段不連續了。重排或歸零的方法 方法1 truncate table 你的表名 這樣不但重新定位自增的字段,而且會將表裡的資料全部刪除,慎用!方法2 delete from 你的表名 dbcc checkident 你的表名,reseed,0 重新定位自增的字段,讓它從...

mysql建立自增字段

1 建立 時新增 create table tablename id int auto increment primary key,2 建立 後新增 alter table tablename add id int auto increment primary key 3 設定主鍵 alter ta...