在某些情况下,临时表可能非常有用,可以保留临时数据.临时表应该知道的最重要的事情是它们将在当前客户端会话终止时被删除.
MySQL版本3.23中添加了临时表.如果您使用的是比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会删除所有临时表.如果你想在它们之间删除它们,那么你可以通过发出 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