Tous les produits
Search
Centre de documentation

PolarDB:ALTER TABLE (mode AUTO)

Dernière mise à jour :Aug 27, 2026

Utilisez l'instruction ALTER TABLE pour modifier le schéma d'une table, par exemple pour ajouter des colonnes, créer des index ou modifier les définitions de colonne. Cette instruction s'applique uniquement aux bases de données en mode AUTO.

Notes d'utilisation

Si la version de votre instance est antérieure à 5.4.17-16835173, vous ne pouvez pas utiliser l'instruction ALTER TABLE pour modifier une clé de sharding.

Syntaxe

Remarque

Pour obtenir la syntaxe détaillée, consultez MySQL ALTER TABLE.

ALTER TABLE tbl_name
    [alter_specification [, alter_specification] ...]
  [partition_options]
  [local_partition_alter_options]

Example

  • Ajouter une colonne

    Ajoutez une colonne nommée idcard à la table user_log :

    ALTER TABLE user_log
        ADD COLUMN idcard varchar(30);
  • Créer un index

    Créez un index nommé idcard_idx sur la colonne idcard de la table user_log :

    ALTER TABLE user_log
        ADD INDEX idcard_idx (idcard);
  • Supprimer un index

    Supprimez l'index idcard_idx de la table user_log :

    ALTER TABLE user_log
        DROP INDEX idcard_idx;
  • Renommer un index

    Renommez l'index idcard_idx en idcard_idx_new sur la table user_log :

    ALTER TABLE user_log
        RENAME INDEX `idcard_idx` TO `idcard_idx_new`;
  • Modifier une colonne

    Modifiez la longueur de la colonne idcard (de type varchar) de 30 à 40 sur la table user_log :

    ALTER TABLE user_log
        MODIFY COLUMN idcard varchar(40);

Index secondaires globaux

PolarDB-X prend en charge les index secondaires globaux (GSI). Pour en savoir plus sur les principes sous-jacents, consultez Index secondaires globaux.

Modifications de colonne

Pour une table dotée d'un GSI, la syntaxe de modification de colonne est identique à celle d'une table classique.

Remarque

Lorsque vous modifiez une colonne dans une table comportant un GSI, des limitations supplémentaires s'appliquent. Pour plus d'informations sur les limitations et les conventions relatives aux GSI, consultez Créer et utiliser des index secondaires globaux.

Modifications d'index

Syntaxe

ALTER TABLE tbl_name
    alter_specification # Only one alter_specification is supported for changes related to global secondary indexes.

alter_specification:
  | ADD GLOBAL {INDEX|KEY} index_name # You must explicitly specify the index name for a global secondary index.
      [index_type] (index_sharding_col_name,...)
      global_secondary_index_option
      [index_option] ...
  | ADD [CONSTRAINT [symbol]] UNIQUE GLOBAL
      [INDEX|KEY] index_name # You must explicitly specify the index name for a global secondary index.
      [index_type] (index_sharding_col_name,...)
      global_secondary_index_option
      [index_option] ...
  | DROP {INDEX|KEY} index_name
  | RENAME {INDEX|KEY} old_index_name TO new_index_name

# For more information about the syntax specific to global secondary indexes, see the CREATE TABLE documentation.
global_secondary_index_option:
    [COVERING (col_name,...)] # Covering Index
    partition_options # Includes only the columns specified in index_sharding_col_name.

# Specify the sharding method for the index table.
partition_options:
    PARTITION BY
          HASH({column_name | partition_func(column_name)})
        | KEY(column_list)
        | RANGE{({column_name | partition_func(column_name)})
        | RANGE COLUMNS(column_list)}
        | LIST{({column_name | partition_func(column_name)})
        | LIST COLUMNS(column_list)} }
    partition_list_spec

# Partition function definitions
partition_func:
    YEAR
  | TO_DAYS
  | TO_SECOND
  | UNIX_TIMESTAMP
  | MONTH

# Partition list definitions
partition_list_spec:
    hash_partition_list
  | range_partition_list
  | list_partition_list

# Column definitions for Hash/Key partitioned tables
hash_partition_list:
    PARTITIONS partition_count

# Column definitions for Range/Range Columns partitioned tables
range_partition_list:
    range_partition [, range_partition ...]

range_partition:
    PARTITION partition_name VALUES LESS THAN {(expr | value_list)} [partition_spec_options]

# Column definitions for List/List Columns partitioned tables
list_partition_list:
    list_partition [, list_partition ...]

list_partition:
    PARTITION partition_name VALUES IN (value_list) [partition_spec_options]

partition_spec_options:
        [[STORAGE] ENGINE [=] engine_name]
        [COMMENT [=] 'string' ]

# The following is MySQL DDL syntax.
index_sharding_col_name:
    col_name [(length)] [ASC | DESC]

index_option:
    KEY_BLOCK_SIZE [=] value
  | index_type
  | WITH PARSER parser_name
  | COMMENT 'string'

index_type:
    USING {BTREE | HASH}

La famille d'instructions ALTER TABLE ADD GLOBAL INDEX permet d'ajouter un GSI à une table existante. Ces instructions utilisent le mot-clé GLOBAL, une extension de la syntaxe MySQL standard, pour spécifier que l'index est un GSI.

Vous pouvez également utiliser l'instruction ALTER TABLE { DROP | RENAME } INDEX pour modifier un GSI. Actuellement, certaines limitations s'appliquent lors de l'ajout d'un GSI à une table existante. Pour plus d'informations sur les limitations et les conventions relatives aux GSI, consultez Créer et utiliser des index secondaires globaux.

Pour plus d'informations sur les clauses de définition des GSI, consultez CREATE TABLE (mode DRDS).

Exemple

  • Ajouter un index secondaire global après la création de la table

    Cet exemple crée un index globalement unique, qui est un type de GSI, sur une table existante.

    # Create a table.
    CREATE TABLE t_order (
      `id` bigint(11) NOT NULL AUTO_INCREMENT,
      `order_id` varchar(20) DEFAULT NULL,
      `buyer_id` varchar(20) DEFAULT NULL,
      `seller_id` varchar(20) DEFAULT NULL,
      `order_snapshot` longtext DEFAULT NULL,
      `order_detail` longtext DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `l_i_order` (`order_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    partition by key(`order_id`)
    partitions 4;
    
    # Create a global secondary index.
    ALTER TABLE t_order ADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`) COVERING (`order_snapshot`) partition by key(`buyer_id`) partitions 4;
    • Table de base : la table t_order est shardée par clé sur la colonne order_id.

    • Table d'index : la table d'index g_i_buyer est shardée par clé sur la colonne buyer_id. La colonne order_snapshot est spécifiée comme colonne de couverture.

    • Clause de définition d'index : UNIQUE GLOBAL INDEX .

    Exécutez SHOW INDEX pour consulter les index de la table de base. La sortie affiche la clé PRIMARY et l'index secondaire local l_i_order, mais pas le GSI. Le GSI lui-même est composé des colonnes suivantes : buyer_id est la clé de sharding de la table d'index ; id (la clé primaire de la table de base) et order_id (la clé de sharding de la table de base) sont incluses comme colonnes de couverture par défaut ; et order_snapshot est une colonne de couverture explicitement spécifiée.

    Remarque

    Pour plus d'informations sur les limitations et les conventions relatives aux GSI, consultez Créer et utiliser des index secondaires globaux. Pour plus d'informations sur SHOW INDEX, consultez SHOW INDEX.

    show index from t_order;
    +--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | Table              | Non_unique | Key_name  | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
    +--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | t_order_syes_00000 |          0 | PRIMARY   |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    | t_order_syes_00000 |          1 | l_i_order |            1 | order_id    | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
    +--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    2 rows in set (0.05 sec)

    Exécutez SHOW GLOBAL INDEX pour afficher uniquement les informations relatives au GSI. Pour plus d'informations, consultez SHOW GLOBAL INDEX.

    show global index;
    +--------+---------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
    | SCHEMA | TABLE   | NON_UNIQUE | KEY_NAME        | INDEX_NAMES | COVERING_NAMES               | INDEX_TYPE | DB_PARTITION_KEY | DB_PARTITION_POLICY | DB_PARTITION_COUNT | TB_PARTITION_KEY | TB_PARTITION_POLICY | TB_PARTITION_COUNT | STATUS |
    +--------+--------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
    | d1     | t_order | 0          | g_i_buyer_$c1a0 | buyer_id    | id, order_id, order_snapshot | NULL       |                  |                     | NULL               |                  |                     | NULL               | PUBLIC |
    +--------+---------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
    1 row in set (0.04 sec)
                            

    Consultez la structure de la table d'index. La table d'index contient la clé primaire et la clé de sharding de la table de base, les colonnes de couverture par défaut et les colonnes de couverture personnalisées. L'attribut AUTO_INCREMENT est supprimé de la colonne de clé primaire, et les index secondaires locaux de la table de base ne sont pas répliqués sur la table d'index. Par défaut, pour appliquer une contrainte d'unicité globale, un index unique est automatiquement créé sur la clé de sharding de la table d'index.

    show create table g_i_buyer;
    +-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | TABLE           | CREATE TABLE                                                                                                                                                                                                                                                                                                                                                  |
    +-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | g_i_buyer_$c1a0 | CREATE TABLE `g_i_buyer_$c1a0` (
        `id` bigint(11) NOT NULL,
        `order_id` varchar(20) DEFAULT NULL,
        `buyer_id` varchar(20) DEFAULT NULL,
        `order_snapshot` longtext,
        UNIQUE KEY `auto_shard_key_buyer_id` USING BTREE (`buyer_id`),
        KEY `_gsi_pk_idx_` USING BTREE (`id`)
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8
    PARTITION BY KEY(`buyer_id`)
    PARTITIONS 4 |
    +-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    1 row in set (0.10 sec)
  • Supprimer un index secondaire global

    Lorsque vous supprimez un GSI, tel que g_i_seller, sa table d'index correspondante est également supprimée.

    # Drop the index.
    ALTER TABLE `t_order` DROP INDEX `g_i_seller`;
  • Renommer un index

    Par défaut, vous ne pouvez pas renommer un GSI. Pour plus d'informations sur les limitations et les conventions relatives aux GSI, consultez Utiliser des index secondaires globaux.