MySQL 临时表
MySQL 临时表
临时表在某些情况下可能非常有用,以保留临时数据。对于临时表应该知道的最重要的事情是,在当前客户端会话终止时,它们将被删除。
在MySQL版本3.23中添加了临时表。如果使用的是旧版本的MySQL,则不能使用临时表,但是可以使用堆表。
正如前面所描述,只要会话还处于活动状态,临时表才会持续。如果您在PHP脚本中运行代码,则在脚本完成执行时,将自动销毁临时表。如果通过MySQL客户端程序连接到MySQL数据库服务器,则临时表将存在,直到您关闭客户端或手动销毁该表为止。
示例:
下面是一个显示临时表使用情况的示例。同样的代码可以在使用mysql_query()函数的PHP脚本中使用。
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删除。如果要在中间删除它们,则通过发出下降命令来执行此操作。
以下是删除临时表的示例:
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