MySQL 临时表

用 TEMPORARY TABLE 存会话级中间结果。

Beginner
Key Points临时表只对当前连接可见、断开即销毁,适合复杂报表的中间计算。

创建与使用

SQL
CREATE TEMPORARY TABLE tmp_top_users (
  id INT, username VARCHAR(50), cnt INT
);
INSERT INTO tmp_top_users
SELECT u.id, u.username, COUNT(*) AS cnt
FROM users u JOIN orders o ON o.user_id = u.id
GROUP BY u.id ORDER BY cnt DESC LIMIT 10;

SELECT * FROM tmp_top_users;
Output
+----+----------+-----+
| id | username | cnt |
+----+----------+-----+
|  1 | alice    |   2 |
+----+----------+-----+
A temp table shadows a normal table of the same name for that session only. It exists only in the creating connection and is dropped on disconnect, so no manual DROP and no cross-session leaks.

Friends & Partners