如何重新排列 MySQL 列?
要重新排列 MySQL 列,请通过 show create 命令检查列排列。语法如下:
show create table yourTableName;
重新排列 MySQL 列的语法如下:
alter table yourTableName change column yourColumnName yourColumnName dataType first
为此,可以使用 after 关键字。语法如下:
alter table yourTableName change column yourColumnName yourColumnName dataType after yourSpecificColumnName;
首先,我们检查已创建表“AddColumn”的列排列:
mysql> show create table AddColumn;
输出如下:
+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AddColumn | CREATE TABLE `addcolumn` (`StudentId` varchar(50) DEFAULT NULL, `StudentName` varchar(300) DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci| +-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
现在可以将 StudentName 列重新排列在 StudentId 之前。查询如下:
mysql> alter table AddColumn change StudentName StudentName varchar(300) first; Query OK, 0 rows affected (1.28 sec) Records: 0 Duplicates: 0 Warnings: 0
以下是用于检查 StudentName 是否为第一列的查询:
mysql> desc AddColumn;
输出如下,显示列已成功重新排列:
+-------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+-------+ | StudentName | varchar(300) | YES | | NULL | | | StudentId | varchar(50) | YES | | NULL | | +-------------+--------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
广告