MySQL實現從記憶位置自增編號

2021-09-26 07:43:41 字數 1287 閱讀 4729

在乙個會員(memberid)中,每位成員(userid)新建乙個或多個文件或者資料夾之類的需要乙個code(例如t0001,在會員中不重複,會員間可以重複),並且是一直往後遞增的,即使使用t0001的使用者被登出了,該編號也不會再次被分配,而是從最大的那乙個編號繼續往後分配。

首先,我們需要用乙個整型來記錄編碼的最後一位,用其他型別的肯定不會存在遞增這種模式。

其次,在整型數前面補充0和其他標記,並轉化為string。

最後,用函式實現遞增,其實直接用**也是可以實現的,但是每次執行時候肯定會多次訪問資料庫,造成鏈結資源的浪費。

資料表結構如下:

其中memberid代表乙個會員,current_value代表當前會員中編號的最大值。

'根據會員id獲得自增id'

begin

declare id int

default0;

select current_value +

1into id from m_code_record where member_id = _member_id for

update

;if id =

0then

set id =1;

insert

into m_code_record (member_id, current_value)

values

(_member_id, id)

;else

update m_code_record set current_value = id where member_id = _member_id;

endif

;return id;

end$$

delimiter

;執行以下函式,獲取下乙個code

mysql 實現id自增序列 mysql自增id列

如果希望在每次插入新記錄時,自動地建立主鍵欄位的值。可以在表中建立乙個 auto increment 字段。mysql 使用 auto increment 關鍵字來執行 auto increment 任務。預設地auto increment 的開始值是 1,每條新記錄遞增 1。主鍵又稱主關鍵字,主關...

mysql實現自增序列

create table sequence name varchar 50 collate utf8 bin not null comment 序列的名字 current value int 11 not null comment 序列的當前值 increment int 11 not null d...

Mysql列自增是怎麼實現的

兩種情況 1 在載入語句執行前,已經不確定要插入多少條記錄。auto inc鎖的作用範圍只是單個插入語句,插入語句執行完成後,這個鎖就被釋放了,跟我們之前介紹的鎖在事務結束時釋放是不一樣的。2 插入語句執行前就確定要插入多少條記錄。innodb中提供系統變數 innodb autoinc lock ...