MySql 中的临时表

来源:互联网 发布:windows updata更新 编辑:程序博客网 时间:2024/05/21 15:36

MySql中的临时表在保存临时数据时非常有用。临时表创建后,若客户端会话终止,临时表将会被删除。

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)

上面的代码创建了一张名为SalesSummary 的临时表,并查询结果。

当使用show tables命令时,并不会显示出创建的临时表。如果在会话结束后执行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 'TUTORIALS.SalesSummary' doesn't exist

当删除临时表后将,再尝试查询将无法查找到数据。

原文地址:http://www.tutorialspoint.com/mysql/mysql-temporary-tables.htm

0 0
原创粉丝点击