Mysql 没有指定主键时,会怎么创建rowid?

 

如果mysql如果不在建表的时候指定索引,会怎么样呢?

 

首先搜索了博客,得到了官方文档翻译:

If you do not define a PRIMARY KEY for your table, MySQL picks the first UNIQUE index that has only NOT NULL columns as the primary key and InnoDB uses it as the clustered index. If there is no such index in the table, InnoDB internally generates a clustered index where the rows are ordered by the row ID that InnoDB assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in insertion order. 

Innodb表中在没有默认主键的情况下会生成一个6byte空间的自动增长主键,可以用select _rowid from table来查询。当在表里设置了主键之后,_rowid就是对应主键,select _rowid from table查询的是对应的主键值.

然后再去文档中搜索,得到了:

如果在创建表时没有显式地定义主键,则InnoDB存储引擎会按如下方式选择或创建主键:

1 首先判断表中是否有非空的唯一索引,如果有,则该列即为主键.

2 如果不符合上述条件,InnoDB存储引擎自动创建一个6字节大小的指针.

得到的资料基本够了,然后去测试:

drop table zz;
CREATE TABLE `zz` (
  `a` varchar(8) COLLATE utf8mb4_unicode_ci NOT NULL,
  `b` varchar(8) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `c` varchar(8) COLLATE utf8mb4_unicode_ci NOT NULL,
  `d` varchar(8) COLLATE utf8mb4_unicode_ci NOT NULL,
  UNIQUE KEY `uid2` (`d`),
  UNIQUE KEY `uid3` (`c`),
  UNIQUE KEY `uid1` (`b`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
insert into zz(a,b,c,d) values('1','2','3','4');


select a,b,c,d,_rowid from zz;

最后结果是:

select a,b,c,d,_rowid from zz;
[Err] 1054 - Unknown column '_rowid' in 'field list'

什么鬼?!!!然后又去搜索了一番.很多人都有这种反馈.但是文档就是这么写的.会有什么错呢??是不是与文档中的 自动增长主键

有关系呢??然后将建表语句中的字段类型改成了int.查询后结果:

abcd_rowid
12344

 

所以结果是:

当创建表时没有显示定义主键时.

1 首先判断表中是否有非空的整形唯一索引,如果有,则该列为主键(这时候可以使用  select _rowid from table 查询到主键列).

2 如果没有符合条件的则会自动创建一个6字节的主键(该主键是查不到的).


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值