Utilice la instrucción ALTER TABLE para modificar el esquema de una tabla; por ejemplo, para agregar columnas, crear índices o modificar definiciones de columnas. Esta instrucción solo aplica a bases de datos en modo AUTO.
Notas de uso
Si la versión de su instancia es anterior a 5.4.17-16835173, no podrá usar la instrucción ALTER TABLE para modificar una clave de fragmentación.
Sintaxis
Para consultar la sintaxis detallada, consulte MySQL ALTER TABLE.
ALTER TABLE tbl_name
[alter_specification [, alter_specification] ...]
[partition_options]
[local_partition_alter_options]
Example
-
Agregar una columna
Agregue una columna llamada
idcarda la tablauser_log:ALTER TABLE user_log ADD COLUMN idcard varchar(30); -
Crear un índice
Cree un índice llamado
idcard_idxen la columnaidcardde la tablauser_log:ALTER TABLE user_log ADD INDEX idcard_idx (idcard); -
Eliminar un índice
Elimine el índice
idcard_idxde la tablauser_log:ALTER TABLE user_log DROP INDEX idcard_idx; -
Cambiar el nombre de un índice
Cambie el nombre del índice
idcard_idxaidcard_idx_newen la tablauser_log:ALTER TABLE user_log RENAME INDEX `idcard_idx` TO `idcard_idx_new`; -
Modificar una columna
Cambie la longitud de la columna
idcard(una columnavarchar) de 30 a 40 en la tablauser_log:ALTER TABLE user_log MODIFY COLUMN idcard varchar(40);
Índices secundarios globales
PolarDB-X es compatible con el índice secundario global (GSI). Para conocer los principios subyacentes, consulte Global Secondary Indexes.
Cambios en columnas
En una tabla con GSI, la sintaxis para modificar columnas es la misma que se usa en una tabla normal.
Al modificar una columna en una tabla con GSI, aplican limitaciones adicionales. Para obtener más información sobre las limitaciones y convenciones de los GSI, consulte Create and use global secondary indexes.
Cambios en índices
Sintaxis
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 familia de instrucciones ALTER TABLE ADD GLOBAL INDEX agrega un GSI a una tabla existente. Estas instrucciones usan la palabra clave GLOBAL, una extensión de la sintaxis estándar de MySQL, para indicar que el índice es un GSI.
También puede usar la instrucción ALTER TABLE { DROP | RENAME } INDEX para modificar un GSI. Actualmente existen algunas limitaciones al agregar un GSI a una tabla existente. Para obtener más información sobre las limitaciones y convenciones de los GSI, consulte Create and use global secondary indexes.
Para obtener más información sobre las cláusulas de definición de GSI, consulte CREATE TABLE (DRDS mode).
Ejemplo
-
Agregar un índice secundario global después de crear la tabla
Este ejemplo crea un índice global único, un tipo de GSI, en una tabla existente.
# 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;Tabla base: la tabla
t_orderse fragmenta por clave en la columnaorder_id.Tabla de índice: la tabla de índice
g_i_buyerse fragmenta por clave en la columnabuyer_id. La columnaorder_snapshotse especifica como columna de cobertura.Cláusula de definición de índice:
UNIQUE GLOBAL INDEX.
Ejecute
SHOW INDEXpara consultar los índices de la tabla base. El resultado muestra la clave PRIMARY y el índice secundario local l_i_order, pero no el GSI. El GSI está compuesto por las siguientes columnas: buyer_id es la clave de fragmentación de la tabla de índice; id (la clave principal de la tabla base) y order_id (la clave de fragmentación de la tabla base) se incluyen como columnas de cobertura predeterminadas; y order_snapshot es una columna de cobertura especificada de forma explícita.NotaPara obtener más información sobre las limitaciones y convenciones de los GSI, consulte Create and use global secondary indexes. Para obtener más información sobre SHOW INDEX, consulte 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)Ejecute
SHOW GLOBAL INDEXpara consultar únicamente la información del GSI. Para obtener más información, consulte 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)Consulte la estructura de la tabla de índice. Esta tabla contiene la clave principal y la clave de fragmentación de la tabla base, las columnas de cobertura predeterminadas y las columnas de cobertura personalizadas. El atributo AUTO_INCREMENT se elimina de la columna de clave principal, y los índices secundarios locales de la tabla base no se replican en la tabla de índice. De forma predeterminada, para aplicar una restricción de unicidad global, se crea automáticamente un índice único en la clave de fragmentación de la tabla de índice.
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) -
Eliminar un índice secundario global
Cuando elimina un GSI, como
g_i_seller, también se elimina su tabla de índice correspondiente.# Drop the index. ALTER TABLE `t_order` DROP INDEX `g_i_seller`; -
Cambiar el nombre de un índice
De forma predeterminada, no es posible cambiar el nombre de un GSI. Para obtener más información sobre las limitaciones y convenciones de los GSI, consulte Use global secondary indexes.