借助 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: 0
上面我们在列名StudentAge之后设置了列StudentAddress。
以下是检查上述两列是否已更改且不丢失数据的查询 -
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)
以上是如何改变MySQL表的列位置而不丢失列数据?的详细内容。更多信息请关注PHP中文网其他相关文章!