本文介绍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'
);

解决方法

  • 添加隐式主键
    1. 使用如下命令查看参数implicit_primary_key的值是否为ON
      show global variables  like 'implicit_primary_key';
    2. 执行如下命令修改无主键表:
      alter table <表名> engine=innodb;
      说明
      • 执行过程中会禁止数据写入表,但是仍然可以读取。
      • implicit_primary_keyON时,修改表的引擎会自动添加隐式主键。
  • 直接添加主键
    执行如下命令为无主键表添加主键:
    ALTER TABLE <表名> ADD PRIMARY KEY (<需要设为主键的列名>);