教程 > sql 教程 > 阅读:59

sql 临时表——迹忆客-ag捕鱼王app官网

有 rdbms,它支持临时表。临时表是一项很棒的功能,它允许我们使用与典型 sql server 表相同的 select 、update和 join 功能来存储和处理中间结果。

在某些情况下,临时表对于保存临时数据可能非常有用。对于临时表应该知道的最重要的事情是当前客户端会话终止时它们将被删除。

临时表在 mysql 3.23 版本以后可用。如果使用的 mysql 版本低于 3.23,则不能使用临时表,但可以使用堆表。

如前所述,临时表只会在会话处于活动状态时持续存在。如果我们是在 php 脚本中运行代码,则在脚本执行完毕后,临时表将自动销毁。如果是通过mysql客户端程序连接到mysql数据库服务器,那么临时表将一直存在,直到关闭客户端或手动销毁该表。


示例

以下示例展示了临时表的用法。

mysql> create temporary table salessummary (
   -> product_name varchar(50) not null
   -> , total_sales decimal(12,2) not null default 0.00
   -> , avg_unit_price decimal(7,2) not null default 0.00
   -> , total_units_sold int unsigned not null default 0
);
query ok, 0 rows affected (0.00 sec)
mysql> insert into salessummary
   -> (product_name, total_sales, avg_unit_price, total_units_sold)
   -> values
   -> ('cucumber', 100.25, 90, 2);
mysql> select * from salessummary;
 -------------- ------------- ---------------- ------------------ 
| product_name | total_sales | avg_unit_price | total_units_sold |
 -------------- ------------- ---------------- ------------------ 
| cucumber     |      100.25 |          90.00 |                2 |
 -------------- ------------- ---------------- ------------------ 
1 row in set (0.00 sec)

临时表不会在 show tables 命令展示的列表中存在。现在,如果退出 mysql 会话,然后通过脚本发出 select 命令,那么我们将发现数据库中没有可用数据。甚至您的临时表也不存在。


删除临时表

默认情况下,当数据库连接终止时,mysql 会删除所有临时表。尽管如此,如果想在会话期间手动删除它们,那么可以通过drop table命令来实现。

以下是删除临时表的示例。

mysql> create temporary table salessummary (
   -> product_name varchar(50) not null
   -> , total_sales decimal(12,2) not null default 0.00
   -> , avg_unit_price decimal(7,2) not null default 0.00
   -> , total_units_sold int unsigned not null default 0
);
query ok, 0 rows affected (0.00 sec)
mysql> insert into salessummary
   -> (product_name, total_sales, avg_unit_price, total_units_sold)
   -> values
   -> ('cucumber', 100.25, 90, 2);
mysql> select * from salessummary;
 -------------- ------------- ---------------- ------------------ 
| product_name | total_sales | avg_unit_price | total_units_sold |
 -------------- ------------- ---------------- ------------------ 
| cucumber     |      100.25 |          90.00 |                2 |
 -------------- ------------- ---------------- ------------------ 
1 row in set (0.00 sec)
mysql> drop table salessummary;
mysql>  select * from salessummary;
error 1146: table 'mydata.salessummary' doesn't exist

查看笔记

扫码一下
查看教程更方便
网站地图