MySQL临时表


在某些情况下,临时表对于保留临时数据可能非常有用。临时表应该知道的最重要的事情是,当当前客户端会话终止时,它们将被删除。

什么是临时表?


在MySQL 3.23版中添加了临时表。如果你使用的MySQL版本早于3.23,则不能使用临时表,但可以使用堆表(Heap Tables)。

如前所述,临时表仅在会话处于活动状态时才持续存在。如果你在PHP脚本中运行代码,则脚本执行完毕后,临时表将被自动销毁。如果你通过MySQL客户端程序连接到MySQL数据库服务器,则临时表将存在,直到你关闭客户端或手动销毁该表为止。

以下程序是一个示例,向你显示临时表的用法。相同的代码可以在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命令,那么你的临时表将不会在列表中列出。现在,如果你要退出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