新聞中心
MySQL 臨時(shí)表
MySQL 臨時(shí)表在我們需要保存一些臨時(shí)數(shù)據(jù)時(shí)是非常有用的。臨時(shí)表只在當(dāng)前連接可見,當(dāng)關(guān)閉連接時(shí),Mysql會自動(dòng)刪除表并釋放所有空間。

臨時(shí)表在MySQL 3.23版本中添加,如果你的MySQL版本低于 3.23版本就無法使用MySQL的臨時(shí)表。不過現(xiàn)在一般很少有再使用這么低版本的MySQL數(shù)據(jù)庫服務(wù)了。
MySQL臨時(shí)表只在當(dāng)前連接可見,如果你使用PHP腳本來創(chuàng)建MySQL臨時(shí)表,那每當(dāng)PHP腳本執(zhí)行完成后,該臨時(shí)表也會自動(dòng)銷毀。
如果你使用了其他MySQL客戶端程序連接MySQL數(shù)據(jù)庫服務(wù)器來創(chuàng)建臨時(shí)表,那么只有在關(guān)閉客戶端程序時(shí)才會銷毀臨時(shí)表,當(dāng)然你也可以手動(dòng)銷毀。
實(shí)例
以下展示了使用MySQL 臨時(shí)表的簡單實(shí)例,以下的SQL代碼可以適用于PHP腳本的mysql_query()函數(shù)。
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)
當(dāng)你使用 SHOW TABLES命令顯示數(shù)據(jù)表列表時(shí),你將無法看到 SalesSummary表。
如果你退出當(dāng)前MySQL會話,再使用 SELECT命令來讀取原先創(chuàng)建的臨時(shí)表數(shù)據(jù),那你會發(fā)現(xiàn)數(shù)據(jù)庫中沒有該表的存在,因?yàn)樵谀阃顺鰰r(shí)該臨時(shí)表已經(jīng)被銷毀了。
刪除MySQL 臨時(shí)表
默認(rèn)情況下,當(dāng)你斷開與數(shù)據(jù)庫的連接后,臨時(shí)表就會自動(dòng)被銷毀。當(dāng)然你也可以在當(dāng)前MySQL會話使用 DROP TABLE 命令來手動(dòng)刪除臨時(shí)表。
以下是手動(dòng)刪除臨時(shí)表的實(shí)例:
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 'RUNOOB.SalesSummary' doesn't exist
網(wǎng)站欄目:創(chuàng)新互聯(lián)MYSQL教程MySQL臨時(shí)表
文章URL:http://m.fisionsoft.com.cn/article/dhjpsog.html


咨詢
建站咨詢
