MySQL 临时表

MySQL 临时表在我们需要保存一些临时数据时是非常有用的

临时表只在当前连接可见,当关闭连接时,MySQL 会自动删除表并释放所有空间

在 MySQL 中,临时表是一种在当前会话中存在的表,它在会话结束时会自动被销毁

以下示例在之前创建的RoboMaster数据库下进行操作

当前数据库数据

mysql> select * from username;
+------+------------+-----------+
| id   | Username   | Password  |
+------+------------+-----------+
|    1 | steins_xin | 123456    |
|    2 | xin        | 123456789 |
+------+------------+-----------+
2 rows in set (0.00 sec)

示例:

-- 创建临时表
CREATE TEMPORARY TABLE temp_username AS
SELECT * FROM username WHERE id >= 1;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

-- 查询临时表
SELECT * FROM temp_username;
+------+------------+-----------+
| id   | Username   | Password  |
+------+------------+-----------+
|    1 | steins_xin | 123456    |
|    2 | xin        | 123456789 |
+------+------------+-----------+
2 rows in set (0.00 sec)

-- 插入数据到临时表
INSERT INTO temp_username (id, username, password)
VALUES (3, 'test', '123456');
Query OK, 1 row affected (0.00 sec)

-- 查询临时表
SELECT * FROM temp_username;
+------+------------+-----------+
| id   | Username   | Password  |
+------+------------+-----------+
|    1 | steins_xin | 123456    |
|    2 | xin        | 123456789 |
|    3 | test       | 123456    |
+------+------------+-----------+
3 rows in set (0.00 sec)

-- 删除临时表 | 或者关闭连接自动销毁
DROP TEMPORARY TABLE IF EXISTS temp_username;

临时表对于需要在某个会话中存储中间结果集或进行复杂查询时非常有用

临时表的作用范围仅限于创建它的会话。其他会话无法直接访问或引用该临时表。在多个会话之间共享数据时,可以考虑使用普通表而不是临时表

请注意,临时表在会话结束时会被自动删除,但也可以使用 DROP TEMPORARY TABLE 明确删除它,这样可以更早地释放资源

results matching ""

    No results matching ""