Mysql 专题
专题目录
您的位置:database > Mysql专题 > MySQL 临时表
MySQL 临时表
作者:--    发布时间:2019-11-20 19:07:09

mysql 临时表在我们需要保存一些临时数据时是非常有用的。临时表只在当前连接可见,当关闭连接时,mysql会自动删除表并释放所有空间。

临时表在mysql 3.23版本中添加,如果你的mysql版本低于 3.23版本就无法使用mysql的临时表。不过现在一般很少有再使用这么低版本的mysql数据库服务了。

mysql临时表只在当前连接可见,如果你使用php脚本来创建mysql临时表,那每当php脚本执行完成后,该临时表也会自动销毁。

如果你使用了其他mysql客户端程序连接mysql数据库服务器来创建临时表,那么只有在关闭客户端程序时才会销毁临时表,当然你也可以手动销毁。

实例

以下展示了使用mysql 临时表的简单实例,以下的sql代码可以适用于php脚本的mysql_query()函数。

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命令显示数据表列表时,你将无法看到 salessummary表。

如果你退出当前mysql会话,再使用 select命令来读取原先创建的临时表数据,那你会发现数据库中没有该表的存在,因为在你退出时该临时表已经被销毁了。


删除mysql 临时表

默认情况下,当你断开与数据库的连接后,临时表就会自动被销毁。当然你也可以在当前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 'w3cschool.salessummary' doesn't exist
网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册