MySQL - 临时表
什么是临时表?
临时表是在数据库中创建的用于临时存储数据的表。当前客户端会话终止或结束后,这些表将被自动删除。除此之外,如果用户决定手动删除这些表,也可以明确删除它们。您可以像处理永久表一样对临时表执行各种 SQL 操作,包括 CREATE、UPDATE、DELETE、INSERT、JOIN 等。
临时表是在 MySQL 3.23 版中引入的。如果您使用的是低于 3.23 版的 MySQL,则无法使用临时表,但可以使用堆表。
如前所述,临时表仅在会话期间有效。如果您在 PHP 脚本中运行代码,则临时表将在脚本执行完成后自动销毁。如果您通过 MySQL 客户端程序连接到 MySQL 数据库服务器,则临时表将一直存在,直到您关闭客户端或手动销毁该表。
在 MySQL 中创建临时表
在 MySQL 中创建临时表与创建常规数据库表非常相似。但是,我们使用 CREATE TEMPORARY TABLE 语句,而不是 CREATE TABLE。
语法
以下是在 MySQL 中创建临时表的语法 -
CREATE TEMPORARY TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );
示例
首先,我们使用以下查询创建一个名为 CUSTOMERS 的临时表 -
CREATE TEMPORARY TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
与普通表类似,我们可以使用 INSERT 语句将记录插入临时表。这里,我们向上面创建的临时表中插入了三条记录 -
INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ), (2, 'Khilan', 25, 'Delhi', 1500.00 ), (3, 'kaushik', 23, 'Kota', 2000.00 );
执行以下查询以显示临时表 CUSTOMERS 的所有记录。
SELECT * FROM CUSTOMERS;
以下是 CUSTOMERS 表的记录 -
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
当我们发出 SHOW TABLES 命令时,临时表不会显示在表列表中。要验证临时表是否存在,我们需要使用 SELECT 语句来检索其数据。临时表会在会话结束时被删除,因此如果我们退出 MySQL 后再尝试执行 SELECT 命令,我们将无法在数据库中找到该临时表。
在 MySQL 中删除临时表
虽然 MySQL 会在数据库连接结束时自动删除临时表,但我们仍然可以根据需要使用 DROP TEMPORARY TABLE 命令自行删除它们。
语法
以下是在 MySQL 中删除临时表的语法 -
DROP TEMPORARY TABLE table_name;
示例
在下面的查询中,我们将删除上一个示例中创建的临时表 CUSTOMERS -
DROP TEMPORARY TABLE CUSTOMERS;
输出
执行上述查询将产生以下输出 -
Query OK, 0 rows affected (0.00 sec)
验证
现在,让我们通过使用以下查询检索临时表 CUSTOMERS 的记录来验证它 -
SELECT * FROM CUSTOMERS;
由于我们删除了临时表 CUSTOMERS,因此会生成一个错误,提示该表不存在。
ERROR 1146: Table 'TUTORIALS.CUSTOMERS' doesn't exist
使用客户端程序创建临时表
除了使用 MySQL 查询在 MySQL 数据库中创建临时表外,我们还可以使用客户端程序对表执行"TEMPORARY TABLE"操作。
语法
以下是使用各种编程语言在 MySQL 数据库中创建临时表的语法 -
要通过 PHP 程序在 MySQL 数据库中创建临时表,我们需要使用 mysqli 函数 query() 执行 Create Temporary Table 语句,如下所示:-
$sql="CREATE temporary Table table_name(column_name, column_type, ...)"; $mysqli->query($sql);
要通过 Node.js 程序在 MySQL 数据库中创建临时表,我们需要使用 mysql2 库中的 query() 函数执行 Create Temporary Table 语句,如下所示:-
sql="CREATE temporary Table table_name(column_name, column_type, ...)"; con.query(sql);
要通过 Java 程序在 MySQL 数据库中创建临时表,我们需要使用 JDBC 函数 executeUpdate() 执行 Create Temporary Table 语句,如下所示:-
String sql="CREATE temporary Table table_name(column_name, column_type, ...)"; statement.executeQuery(sql);
要通过 Python 程序在 MySQL 数据库中创建临时表,我们需要使用 MySQL Connector/Python 的 execute() 函数执行 Create Temporary Table 语句,如下所示:-
sql="CREATE temporary Table table_name(column_name, column_type, ...)"; cursorObj.execute(sql);
示例
以下是程序 -
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
printf("Connect failed: %s
", $mysqli->connect_error);
exit();
}
// printf('Connected successfully.
');
$sql = "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 )";
if ($mysqli->query($sql)) {
printf("temporary table created successfully.
");
}
if ($mysqli->errno) {
printf("temporary table could not be created: %s
", $mysqli->error);
}
$mysqli->close();
输出
获得的输出如下 -
temporary table created successfully.
var mysql = require('mysql2');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Nr5a0204@123"
});
//连接到 MySQL
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
console.log("--------------------------");
//创建数据库
sql = "CREATE DATABASE testdb"
con.query(sql);
//选择数据库
sql = "USE testdb"
con.query(sql);
//创建表
sql = "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);"
con.query(sql);
sql = "INSERT INTO SalesSummary(product_name, total_sales, avg_unit_price, total_units_sold)VALUES('cucumber', 100.25, 90, 2);"
con.query(sql);
sql = "SELECT * FROM SalesSummary;"
con.query(sql, function(err, result){
if (err) throw err
console.log("**SalesSummary Table:**")
console.log(result);
});
});
输出
生成的输出如下 -
Connected!
--------------------------
**SalesSummary Table:**
[
{
product_name: 'cucumber',
total_sales: '100.25',
avg_unit_price: '90.00',
total_units_sold: 2
}
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TemporaryTable {
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/TUTORIALS";
String username = "root";
String password = "password";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
System.out.println("Connected successfully...!");
//Create temporary table...!
String sql = "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 )";
statement.executeUpdate(sql);
System.out.println("Temporary table created successfully...!");
ResultSet resultSet = statement.executeQuery("DESCRIBE SalesSummary");
while(resultSet.next()) {
System.out.print(resultSet.getNString(1));
System.out.println();
}
connection.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
输出
获得的输出如下所示 -
Connected successfully...! Temporary table created successfully...! product_name total_sales avg_unit_price total_units_sold
import mysql.connector
#建立连接
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='tut'
)
table_name = 'tutorials_tbl_temp'
#创建游标对象
cursorObj = connection.cursor()
create_table_query = f"CREATE TEMPORARY TABLE {table_name} (NAME VARCHAR(50), ID INT)"
cursorObj.execute(create_table_query)
print(f"Temporary table '{table_name}' is created successfully.")
cursorObj.close()
connection.close()
输出
以下是上述代码的输出 -
Temporary table 'tutorials_tbl_temp' is created successfully.

