在 MySQL 中重命名表

本教程将介绍如何重命名 MySQL 数据库中的表。

通常,组织的产品需求会发生变化,因此需要不断更改特定数据库中的表和列的名称。这些更改将有助于反映更新的信息。MySQL 使用多种技术帮助我们有效地执行此操作。

要更改特定表的名称,我们使用 RENAME TABLE 语句,如下所示。

RENAMETABLEold_table_nameTOnew_table_name;

我们可以使用以下两种技术重命名 MySQL 中的表。

  • 使用 RENAME TABLE 方法。
  • 使用 ALTER TABLE 方法。

在开始之前,我们创建一个虚拟数据集来使用。在这里,我们创建了一个表 student_details 以及几行。

-- create the table student_details
CREATETABLEstudent_details(stu_idint,stu_firstNamevarchar(255)DEFAULTNULL,stu_lastNamevarchar(255)DEFAULTNULL,primarykey(stu_id));-- insert rows to the table student_details
INSERTINTOstudent_details(stu_id,stu_firstName,stu_lastName)VALUES(1,"Preet","Sanghavi"),(2,"Rich","John"),(3,"Veron","Brow"),(4,"Geo","Jos"),(5,"Hash","Shah"),(6,"Sachin","Parker"),(7,"David","Miller");

现在让我们将 student_details 表重命名为 student_information 表。

在 MySQL 中使用 RENAME 语句重命名表

我们可以使用 rename 语句来完成这项工作。该语句可以写成 RENAME previous_table_name to new_name_to_be_assigned; 在 MySQL 中。为了对 student_details 表执行上述操作,我们可以使用以下查询。

RENAMETABLEstudent_detailsTOstudent_information;

现在,让我们使用以下查询检查 student_information 表。

SELECT*fromstudent_information;

上面提到的查询将为我们提供以下输出。

stu_idstu_firstNamestu_lastName1PreetSanghavi2RichJohn3VeronBrow4GeoJos5HashShah6SachinParker7DavidMiller

它表明表已成功重命名,表数据中没有任何争执。

在 MySQL 中使用 ALTER TABLE 语句重命名表

我们还可以使用 MySQL 中的 ALTER TABLE 语句来重命名表。此操作的语法如下所示。

ALTERTABLEprevious_table_nameRENAMEnew_name_to_be_assigned;

为了使用 ALTER TABLE 技术重命名 student_details 表,我们可以使用以下查询。

ALTERTABLEstudent_detailsRENAMEstudent_information;

现在,让我们使用以下查询检查 student_information 表。

SELECT*fromstudent_information;

上面提到的查询将为我们提供以下输出。

stu_idstu_firstNamestu_lastName1PreetSanghavi2RichJohn3VeronBrow4GeoJos5HashShah6SachinParker7DavidMiller