您好,欢迎访问一九零五行业门户网

详解MySQL临时表的功能及实例代码

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 'tutorials.salessummary' doesn't exist
【相关推荐】
1. 特别推荐:“php程序员工具箱”v0.1版本下载
2. 免费mysql在线视频教程
3. 数据库设计那些事
以上就是详解mysql临时表的功能及实例代码的详细内容。
其它类似信息

推荐信息