如何在不丟失列資料的情況下更改MySQL表的列位置?


您可以使用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

我們在上面將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)

更新於:2019年7月30日

10K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.