MySQL 临时表
讲解 MySQL TEMPORARY TABLE 临时表的会话级生命周期、显式建表与 CTAS 创建语法、CRUD/ALTER/DROP 操作、与 SHOW TABLES 的隔离特征及多连接不可见实测。
学完这一章,你能够
- 讲解 MySQL TEMPORARY TABLE 临时表的会话级生命周期、显式建表与 CTAS 创建语法、CRUD/ALTER/DROP 操作、与 SHOW TABLES 的隔离特征及多连接不可见实测。
临时表的会话可见性与生命周期
MySQL 临时表(Temporary Table)专门用于保存单次会话内的中间计算结果或临时数据集。它的两大核心特性是:仅对创建它的当前数据库连接可见,其他并发会话既看不到也不会与其同名冲突;一旦客户端断开连接(例如一次 PHP 短连接脚本执行结束或命令行客户端退出),MySQL 会自动销毁该临时表并回收存储空间。
创建、读写、修改与删除临时表语法
创建临时表只需在 `CREATE TABLE` 之间加入 `TEMPORARY` 关键字:`CREATE TEMPORARY TABLE temp_name (col1 datatype, ...);`,也可以直接基于查询结果建表:`CREATE TEMPORARY TABLE temp_name AS SELECT ... FROM source_table WHERE condition;`。建成后对其执行 `INSERT`、`SELECT`、`UPDATE`、`DELETE` 和 `ALTER TABLE` 的方式与普通表一致;如需在会话结束前尽早释放内存或磁盘,应使用 `DROP TEMPORARY TABLE IF EXISTS temp_name;`(带 `TEMPORARY` 关键字可避免误删同名持久化普通表)。
在订单筛选示例中,先用 `CREATE TEMPORARY TABLE temp_orders AS SELECT * FROM orders WHERE order_date >= '2023-01-01';` 抽取中间结果,随后向临时表追加一条测试订单并查询,最后手动 `DROP` 清理。切记临时表无法跨会话共享数据,若多个请求或服务实例需要共用中间表,应改用普通表并配合任务标识列隔离。
SalesSummary 实例、目录隐藏与断连销毁实测
在 `SalesSummary` 实例中,创建含商品名称、总销售额、平均单价与销量的临时表并写入 `('cucumber', 100.25, 90, 2)` 后,当前会话可正常 `SELECT` 读出该行,但执行 `SHOW TABLES` 时不会列出任何临时表(注意原文提及的 `mysql_query()` 为 PHP 旧扩展函数,现代 PHP 应使用 `mysqli` 或 `PDO`)。手动执行 `DROP TEMPORARY TABLE SalesSummary` 或退出会话重连后再次查询,均会返回表不存在错误(MySQL 错误码 1146)。本地 SQLite 3.53.1 在独立临时库上通过双连接实测:完整验证了 CTAS、`ALTER TABLE`、主目录 `sqlite_master` 隐藏(仅见于 `sqlite_temp_master`)、第二连接不可见以及原连接关闭后自动销毁。
在本地 SQLite 3.53.1 实测临时表 CTAS、ALTER/DROP、目录隐藏与多会话隔离销毁
"""Offline SQLite verifier for MySQL Chapter 26: Temporary Tables."""
import json
import sqlite3
import sys
import tempfile
from pathlib import Path
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
# 1. CREATE TEMPORARY TABLE explicit schema & CTAS (AS SELECT)
cur.executescript(
"""
CREATE TABLE orders (
order_id INT,
customer_id INT,
order_date TEXT
);
INSERT INTO orders VALUES
(999, 1, '2022-12-20'),
(1000, 2, '2023-01-02');
CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL,
total_sales REAL NOT NULL DEFAULT 0.00,
avg_unit_price REAL NOT NULL DEFAULT 0.00,
total_units_sold INT NOT NULL DEFAULT 0
);
INSERT INTO SalesSummary (product_name, total_sales, avg_unit_price, total_units_sold)
VALUES ('cucumber', 100.25, 90.0, 2);
CREATE TEMPORARY TABLE temp_orders AS
SELECT * FROM orders WHERE order_date >= '2023-01-01';
INSERT INTO temp_orders (order_id, customer_id, order_date)
VALUES (1001, 1, '2023-01-05');
"""
)
sales_rows = [list(r) for r in cur.execute("SELECT * FROM SalesSummary").fetchall()]
temp_order_rows = [
list(r) for r in cur.execute("SELECT * FROM temp_orders ORDER BY order_id").fetchall()
]
case1 = make_case(
"temp_table_create_crud_and_ctas",
"Verify explicit CREATE TEMPORARY TABLE and CREATE TEMPORARY TABLE ... AS SELECT with INSERT/SELECT",
{
"sales_summary": [["cucumber", 100.25, 90.0, 2]],
"temp_orders": [[1000, 2, "2023-01-02"], [1001, 1, "2023-01-05"]],
},
{
"sales_summary": sales_rows,
"temp_orders": temp_order_rows,
},
)
# 2. ALTER TABLE and manual DROP TABLE on temporary table
cur.execute("ALTER TABLE temp_orders ADD COLUMN note TEXT DEFAULT 'ok'")
altered_cols = [r[1] for r in cur.execute("PRAGMA table_info(temp_orders)").fetchall()]
cur.execute("DROP TABLE IF EXISTS temp_orders")
query_after_drop_failed = False
try:
cur.execute("SELECT * FROM temp_orders")
except sqlite3.OperationalError:
query_after_drop_failed = True
case2 = make_case(
"temp_table_alter_and_drop",
"Verify ALTER TABLE adds column to temporary table and DROP TABLE immediately removes it",
{
"altered_cols": ["order_id", "customer_id", "order_date", "note"],
"query_after_drop_failed": True,
},
{
"altered_cols": altered_cols,
"query_after_drop_failed": query_after_drop_failed,
},
)
# 3. Temporary table absent from main schema catalog (analogous to SHOW TABLES)
main_tables = [
r[0] for r in cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
]
temp_tables = [
r[0] for r in cur.execute("SELECT name FROM sqlite_temp_master WHERE type='table'").fetchall()
]
case3 = make_case(
"temp_table_hidden_from_main_schema",
"Verify SalesSummary is hidden from main sqlite_master (like SHOW TABLES) and isolated in temp catalog",
{
"in_main_schema": False,
"in_temp_schema": True,
},
{
"in_main_schema": "SalesSummary" in main_tables,
"in_temp_schema": "SalesSummary" in temp_tables,
},
)
conn.close()
# 4. Session isolation and auto-destroy on disconnect (using isolated TemporaryDirectory)
with tempfile.TemporaryDirectory() as tmp:
db_path = Path(tmp) / "session_isolation.sqlite"
c1 = sqlite3.connect(db_path)
c2 = sqlite3.connect(db_path)
c1.execute("CREATE TABLE persistent_tbl (id INT)")
c1.commit()
c1.execute("CREATE TEMPORARY TABLE session_only (v TEXT)")
c1.execute("INSERT INTO session_only VALUES ('private')")
c1_sees = c1.execute("SELECT v FROM session_only").fetchone()[0]
c2_blocked = False
try:
c2.execute("SELECT * FROM session_only")
except sqlite3.OperationalError:
c2_blocked = True
c1.close()
c2.close()
c3 = sqlite3.connect(db_path)
destroyed_after_close = False
try:
c3.execute("SELECT * FROM session_only")
except sqlite3.OperationalError:
destroyed_after_close = True
c3.close()
case4 = make_case(
"temp_table_session_isolation",
"Verify temporary table is visible only to creator session and auto-destroyed when session closes",
{
"creator_sees": "private",
"other_session_blocked": True,
"destroyed_after_close": True,
},
{
"creator_sees": c1_sees,
"other_session_blocked": c2_blocked,
"destroyed_after_close": destroyed_after_close,
},
)
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认 SalesSummary 与 temp_orders 读写、加列与删除、主目录隐藏、双连接跨会话隔离以及断连后自动销毁全部通过。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
当前源码 SHA256:355a2f254ae64ab2e77033d00ce55c97b4b6440a24f11d73dd510642c65f6d82
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
ZIP SHA256:fce7ade243d91f7c9488338f34158ac6209f22e3797e1a47a02d330541d12d99
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在手动清理临时表时更推荐使用 `DROP TEMPORARY TABLE IF EXISTS t` 而不是简写 `DROP TABLE t`?
展开参考解答
因为若会话中恰好存在与临时表同名的持久化普通表(临时表会遮蔽同名普通表),一旦临时表尚未创建或已被删除,不带 `TEMPORARY` 的 `DROP TABLE t` 会把同名持久化普通表误删;加上 `TEMPORARY` 可确保只删除临时表。