SQL 临时表


RDBMS支持临时表,可让你存储和处理中间结果

在某些情况下,临时表对于保存临时数据可能非常有用,但当当前客户端会话终止时它们将被删除。

临时表在 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)

当你发出 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