相關免費學習推薦:mysql視頻教程
通過我自己的一番實戰,可以確定的是,只要創建表,這個rowid一定是存在的,唯一區別就是顯示和隱士的區別,也就是是否可以通過select _rowid from table查詢出來
那么問題來了,哪些情況下rowid是顯示的?
1 、當表中有主鍵並且是數值型的時候才是顯示的
2、當表中沒有主鍵的時候,但是表中有唯一非空並且是數值型的時候才是顯示的
接下來,創建表來實戰看下,是否是這樣的先創建一個帶有主鍵並且是數值型的表
create table z1(
id bigint(20) primary key
)engine=innodb;
再創建一個帶有主鍵不是數值型的表(雖然業務不會這樣創建,只是為了證明rowid)
create table z2(
name varchar(20) primary key
)engine=innodb;
再創建一個沒有主鍵但是有唯一鍵並且是數值型非空的表
create table z3(
name int(11) not null,
unique(name)
)engine=innodb charset=utf8
此時再創建一個沒有主鍵,並且有唯一鍵,但是可以為空或者不是數值型的表
create table z4(
name varchar(11) not null,
unique(name)
)engine=innodb charset=utf8;
create table z5(
name int(11) ,
unique(name)
)engine=innodb charset=utf8;
再來看看官網咋說的,再理解下
官網連接:https://dev.mysql.com/doc/refman/5.7/en/create-index.html
If a table has a PRIMARY KEY or UNIQUE NOT NULL index that consists of a single column that has an integer type, you can use _rowid to refer to the indexed column in SELECT statements, as follows:
_rowid refers to the PRIMARY KEY column if there is a PRIMARY KEY consisting of a single integer column. If there is a PRIMARY KEY but it does not consist of a single integer column, _rowid cannot be used.
Otherwise, _rowid refers to the column in the first UNIQUE NOT NULL index if that index consists of a single integer column. If the first UNIQUE NOT NULL index does not consist of a single integer column, _rowid cannot be used.此時我再創建一個表,表中只有一個字段,並且是字符串類型的,看下生成的隱式rowid,達到最大值會發生什么?(注意此時底層會默認生成一個6字節的指針,最大值為2^48 次冪)
此時用gdb工具讓rowid達到最大值再插入看看會怎么樣?
答:先找到mysqld的進程pid,命令
ps aux | grep mysqld
gdb -p 你的mysql的pid -ex 'p dict_sys->row_id=1' -batch
可以看到此時插入了3條數據
這個時候把rowid變為2^48次冪之后,再插入看下效果
gdb -p 29410 -ex 'p dict_sys->row_id=281474976710656' -batch
此時再插入三條數據,此時a1 a2被覆蓋了,所以在不滿足上述二種情況的時候,生成的隱式rowid在用盡之后,之前的記錄會被覆蓋,所以創建表一定要有主鍵id,避免發生覆蓋,雖然概率比較低,這個只是用主鍵的其中一個原因哈
所以綜上所述:看我xmind那個總結,自己再理解消化下吧。