首页 > 文章列表 > 我们可以改变 MySQL 中列的顺序吗?

我们可以改变 MySQL 中列的顺序吗?

353 2023-09-04

是的,我们可以更改列的顺序。这可以使用 ALTER 命令和 AFTER 命令来设置单个列的新顺序。让我们首先创建一个表 -

mysql> create table DemoTable
   -> (
   -> `Student_Key_Age` int,
   -> `Student_Key_Name` varchar(20),
   -> `Student_Key_CountryName` varchar(20)
   -> );
Query OK, 0 rows affected (0.64 sec)

以下是更改列顺序的查询 -

mysql> alter table DemoTable modify column `Student_Key_Age` int after `Student_Key_Name`;
Query OK, 0 rows affected (1.15 sec)
Records: 0 Duplicates: 0 Warnings: 0

让我们再次检查表格描述 -

mysql> desc DemoTable;

这将产生以下输出。正如您所看到的,列的顺序发生了变化 -

+-------------------------+-------------+------+-----+---------+-------+
| Field                   | Type        | Null | Key | Default | Extra |
+-------------------------+-------------+------+-----+---------+-------+
| Student_Key_Name        | varchar(20) | YES  |      | NULL   |       |
| Student_Key_Age         | int(11)     | YES  |      | NULL   |       |
| Student_Key_CountryName | varchar(20) | YES  |      | NULL   |       |
+-------------------------+-------------+------+-----+---------+-------+
3 rows in set (0.11 sec)