mysql 自增列相關問題整理

2021-05-21 23:12:08 字數 1678 閱讀 1391

mysql自增列

1.關鍵字 :auto_increment

2.自增用法

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

name char(30) not null,

primary key (id));

3.關於自增

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

a:select @@identity

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

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().

4.如何重置種子到1:

truncate 重置種子值到「1」 。

5.select * from table_name where auto_increment_col_name is null 獲得最後插入的第一行資料;即使一次性插大批資料也是只返回該批次第一行自增後的值!

特殊的:對於myisam表,特殊的對於myisam引擎的表,你可以在乙個多列索引上的第二列上定義自增列:將在第一索引列上產生自增,可以理解為:在第一索引列上分組,計算該組上的最大值,+1。該形式下:(分組)自增列的種子值總是取該列上的分組 最大值——受delete、update、insert影響。

mysql 自增列相關問題整理

mysql自增列 1.關鍵字 auto increment 2.自增用法 例 create table animals id mediumint not null auto increment,name char 30 not null,primary key id 3.關於自增 q 怎麼獲得當前的...

MySQL 自增列持久化問題

自增列持久化問題 5.5 5.6 5.7三個版本中,mysql並不會將自增列分配的自增值資訊固化到磁碟,當mysql重啟後,會根據自增列上當前最大值和引數auto increment offset來確定下一次的自增值,為快速獲取自增列上最大值,mysql要求自增列必須建有索引。如果一張自增表的資料在...

Mysql 自增列 主鍵

mysql中假如有 id int auto increment,cid varchar 36 通常情況下都是 id設定為主鍵。假如要設定cid為主鍵。自增列id必需是唯一索引。create table temp id bigint not null auto increment comment 編號...