在 MySQL 中创建临时表
在本教程中,我们旨在探索在 MySQL 中创建临时表的不同方法。
临时表的主要功能之一是它有助于存储临时数据。此功能在 MySQL 3.23 及更高版本中启用。
当用户手动删除表或会话结束时,这些表将丢失。
临时表的另一个特点是可以在多个连接中使用同名的表。这是因为客户端只能处理他们创建的临时表。
在 MySQL 中创建临时表主要有两种方式:
- 基本的临时表创建。
- 从
SELECT
查询创建临时表。
然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,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");
上面的查询创建了一个表以及其中包含学生名字和姓氏的行。为了查看数据中的条目,我们使用以下代码:
SELECT*FROMstudent_details;
上面的代码将给出以下输出:
stu_idstu_firstNamestu_lastName1PreetSanghavi2RichJohn3VeronBrow4GeoJos5HashShah6SachinParker7DavidMiller
现在,让我们创建一个名为 students_temporary
的临时表,类似于 student_details
表。
在 MySQL 中创建基本临时表
创建临时表的最基本方法之一是使用 TEMPORARY
关键字。我们可以创建一个名为 students_teporary
的临时表,如下所示:
-- Basic temporary table creation
CREATETEMPORARYTABLEstudents_teporary(stu_idint,stu_firstNamevarchar(255)DEFAULTNULL,stu_lastNamevarchar(255)DEFAULTNULL,primarykey(stu_id));
上面的代码创建了一个名为 students_temporary
的临时表。接下来,让我们使用以下代码在此表中插入一些条目:
-- 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");
上述代码的输出结果是一个临时表,如下所示:
stu_idstu_firstNamestu_lastName1PreetSanghavi2RichJohn3VeronBrow4GeoJos5HashShah6SachinParker7DavidMiller
从 SELECT
查询创建临时表
创建临时表的另一种方法是使用 select 语句。这种方法帮助我们将整个表复制到具有相同实体和数据类型的临时表中。让我们尝试使用 SELECT
语句创建一个临时表 students_details_temporary
。我们可以用下面的代码来做到这一点。
-- Replicating the students_details table
CREATETEMPORARYTABLEIFNOTEXISTSstudents_details_temporaryAS(SELECT*FROMstudents_details);
注意
在上面的查询中,我们使用
IF NOT EXISTS
来确保数据库中没有名为 student_details_temporary
的表。上述代码将给出以下输出:
stu_id stu_firstName stu_lastName
1 Preet Sanghavi
2 Rich John
3 Veron Brow
4 Geo Jos
5 Hash Shah
6 Sachin Parker
7 David Miller
如我们所见,已生成具有与原始表 (student_details
) 相同的实体和条目的临时表。
因此,借助上述两种方法,我们可以高效地创建临时表。一旦最后一个连接终止,这个临时表就会被删除。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。