臨時(shí)表可能是非常有用的,在某些情況下,保持臨時(shí)數(shù)據(jù)。最重要的是應(yīng)該知道的臨時(shí)表是,他們將當(dāng)前的客戶(hù)端會(huì)話終止時(shí)被刪除。
臨時(shí)表中添加MySQL版本3.23。如果您使用的是舊版本的MySQL比3.23,可以不使用臨時(shí)表,但可以使用堆表。
如前所述臨時(shí)表將只持續(xù)只要的會(huì)話是存在的。如果運(yùn)行一個(gè)PHP腳本中的代碼,該臨時(shí)表將被銷(xiāo)毀時(shí),會(huì)自動(dòng)執(zhí)行完腳本后。如果已連接到MySQL數(shù)據(jù)庫(kù)的服務(wù)器上,通過(guò)MySQL的客戶(hù)端程序的臨時(shí)表將一直存在,直到關(guān)閉客戶(hù)端或手動(dòng)破壞的表。
實(shí)例
下面是一個(gè)例子,使用臨時(shí)表在PHP腳本中,使用mysql_query()函數(shù),可以使用相同的代碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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)發(fā)出一個(gè)SHOW TABLES命令,那么臨時(shí)表將不會(huì)被列在列表中。現(xiàn)在如果將MySQL的會(huì)話的注銷(xiāo),那么會(huì)發(fā)出SELECT命令,那么會(huì)發(fā)現(xiàn)沒(méi)有在數(shù)據(jù)庫(kù)中的數(shù)據(jù)。即使臨時(shí)表也就不存在了。
刪除臨時(shí)表:
默認(rèn)情況下,所有的臨時(shí)表被刪除時(shí),MySQL的數(shù)據(jù)庫(kù)連接被終止。不過(guò)要?jiǎng)h除他們之前就應(yīng)該發(fā)出DROP TABLE命令。
下面的例子為刪除一個(gè)臨時(shí)表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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 |