Home  >  Article  >  Database  >  MySQL中关于临时表的一些基本使用方法_MySQL

MySQL中关于临时表的一些基本使用方法_MySQL

WBOY
WBOYOriginal
2016-06-01 13:00:23995browse

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

临时表中添加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 'TUTORIALS.SalesSummary' doesn't exist


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn