发布于 2015-07-31 16:25:13 | 486 次阅读 | 评论: 0 | 来源: 网络整理

临时表可能在某些情况下是非常有用的,以保持临时数据。 临时表的最重要的事情是,当前客户端会话结束时,它们将会被删除。

临时表是在MySQL版本3.23中增加的。如果使用MySQL 3.23之前的旧版本,是不能使用临时表的,但可以使用堆表。

如前所述,临时表将只持续在会话存在时。如果在运行一个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 'test.SalesSummary' doesn't exist
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务