本文介绍RDS for MySQL的表在没有主键时如何添加主键。
查看无主键表
执行如下命令查看是否有无主键表: 
select table_schema,table_name from information_schema.tables
where (table_schema,table_name) not in(
select distinct table_schema,table_name from information_schema.columns where COLUMN_KEY='PRI'
)
and table_schema not in (
'sys','mysql','information_schema','performance_schema'
);
解决方法
- 添加隐式主键
- 使用如下命令查看参数implicit_primary_key的值是否为ON。
show global variables like 'implicit_primary_key';
- 执行如下命令修改无主键表:
alter table <表名> engine=innodb;说明- 执行过程中会禁止数据写入表,但是仍然可以读取。
- 当implicit_primary_key为ON时,修改表的引擎会自动添加隐式主键。
- 使用如下命令查看参数implicit_primary_key的值是否为ON。
- 查看隐式主键
无主键表添加隐式主键后,隐式主键列(
__#alibaba_rds_row_id#__)默认不可见,需在会话级别设置show_ipk_info参数后才能查看。执行如下命令开启隐式主键显示:
SET show_ipk_info = on;说明show_ipk_info默认值为off,仅支持会话级别设置,不支持全局设置。通过
SHOW CREATE TABLE查看隐式主键:SHOW CREATE TABLE <表名>;返回结果中
__#alibaba_rds_row_id#__列即为隐式主键,类型为bigint NOT NULL AUTO_INCREMENT。通过
information_schema.columns查询隐式主键:SELECT * FROM information_schema.columns WHERE table_name = '<表名>' AND column_name = '__#alibaba_rds_row_id#__';执行如下命令查询隐式主键最大值:
SELECT MAX(`__#alibaba_rds_row_id#__`) FROM <表名>;
- 直接添加主键 执行如下命令为无主键表添加主键:
ALTER TABLE <表名> ADD PRIMARY KEY (<需要设为主键的列名>);
该文章对您有帮助吗?