如何在不丢失列数据的情况下更改 MySQL 表的列位置?
mysqlmysqli database
您可以借助 ALTER TABLE 命令更改 MySQL 表的列位置而不丢失数据。语法如下 −
ALTER TABLE yourTableName MODIFY yourColumnName1 data type AFTER yourColumnName2;
为了理解上述概念,让我们创建一个表。创建包含一些列的表的查询如下 −
mysql> create table changeColumnPositionDemo −> ( −> StudentId int, −> StudentAddress varchar(200), −> StudentAge int, −> StudentName varchar(200) −> ); Query OK, 0 rows affected (0.72 sec)
让我们在表中插入一些数据。插入记录的查询如下 -
mysql> insert into changeColumnPositionDemo values(101,'US',23,'Johnson'); Query OK, 1 row affected (0.13 sec) mysql> insert into changeColumnPositionDemo values(102,'UK',20,'John'); Query OK, 1 row affected (0.19 sec) mysql> insert into changeColumnPositionDemo values(103,'US',22,'Carol'); Query OK, 1 row affected (0.39 sec) mysql> insert into changeColumnPositionDemo values(104,'UK',19,'Sam'); Query OK, 1 row affected (0.18 sec)
现在您可以借助 select 语句显示所有记录。查询如下 −
mysql> select *from changeColumnPositionDemo;
以下是输出 -
+-----------+----------------+------------+-------------+ | StudentId | StudentAddress | StudentAge | StudentName | +-----------+----------------+------------+-------------+ | 101 | U | 23 | Johnson | | 102 | UK | 20 | John | | 103 | US | 22 | Carol | | 104 | UK | 19 | Sam | +-----------+----------------+------------+-------------+ 4 rows in set (0.00 sec)
以下是更改列位置而不丢失数据的查询。我们将“StudentAddress”列移至“StudentAge”列之后−
mysql> ALTER TABLE changeColumnPositionDemo MODIFY StudentAddress varchar(200) AFTER StudentAge; Query OK, 0 rows affected (2.27 sec) Records: 0 Duplicates: 0 Warnings: 00
以上我们将列 StudentAddress 设置在列名 StudentAge 之后。
以下是检查上述两列是否已更改而不丢失数据的查询 −
mysql> select *from changeColumnPositionDemo;
以下是输出 −
+-----------+------------+----------------+-------------+ | StudentId | StudentAge | StudentAddress | StudentName | +-----------+------------+----------------+-------------+ | 101 | 23 | US | Johnson | | 102 | 20 | UK | John | | 103 | 22 | US | Carol | | 104 | 19 | UK | Sam | +-----------+------------+----------------+-------------+ 4 rows in set (0.00 sec)