RDS for MySQL为无主键表添加主键

更新时间:
复制 MD 格式

本文介绍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_key为ON时,修改表的引擎会自动添加隐式主键。
  • 查看隐式主键

    无主键表添加隐式主键后,隐式主键列(__#alibaba_rds_row_id#__)默认不可见,需在会话级别设置show_ipk_info参数后才能查看。

    1. 执行如下命令开启隐式主键显示:

      SET show_ipk_info = on;
      说明

      show_ipk_info默认值为off,仅支持会话级别设置,不支持全局设置。

    2. 通过SHOW CREATE TABLE查看隐式主键:

      SHOW CREATE TABLE <表名>;

      返回结果中__#alibaba_rds_row_id#__列即为隐式主键,类型为bigint NOT NULL AUTO_INCREMENT。

    3. 通过information_schema.columns查询隐式主键:

      SELECT * FROM information_schema.columns WHERE table_name = '<表名>' AND column_name = '__#alibaba_rds_row_id#__';
    4. 执行如下命令查询隐式主键最大值:

      SELECT MAX(`__#alibaba_rds_row_id#__`) FROM <表名>;
  • 直接添加主键
    执行如下命令为无主键表添加主键:
    ALTER TABLE <表名> ADD PRIMARY KEY (<需要设为主键的列名>);