036、TiDB特性_临时表

全局临时表

CREATE GLOBAL TEMPORARY TABLE;
  • 全局临时表的表定义是持久的,并且对所有会话都可⻅
  • 全局临时表的数据仅在当前事务中可⻅
  • 当事务结束时,数据会⾃动清除
  • 全局临时表不能与永久表同名
  • 出现在 information_schema.tables

# commit delete rows 一定带上这个才能创建
tidb> create global temporary table test.temp2 (id bigint) on
commit delete rows;
Query OK, 0 rows affected (0.57 sec)

# 开启事务,关闭自动提交
tidb> set @@autocommit = 'OFF';
tidb> insert into test.temp2 values (10);
tidb> select * from test.temp2;
+------+
| id |
+------+
| 10 |
+------+
1 row in set (0.00 sec)
tidb> commit;

# 事务完成后,这张表虽然存在,但里面的数据清掉
tidb> select * from test.temp2;
Empty set (0.00 sec)

用户可通过 CREATE GLOBAL TEMPORARY TABLE 语句创建全局临时表,语句末尾要加上 ON COMMIT DELETE ROWS。可通过 DROP TABLE 或 DROP GLOBAL TEMPORARY TABLE 语句删除全局临时表。

本地临时表

  • CREATE TEMPORARY TABLE:

    • 仅在客户端会话期间存在
    • 仅对创建它的会话可见
    • 覆盖永久表的定义
    • 不会出现在 information_schema.tables
  • 本地临时表的语义与 MySQL 临时表一致,它有以下特性:

    • 本地临时表的表定义不持久化,只在创建该表的会话内可见,其他会话无法访问该本地临时表
    • 不同会话可以创建同名的本地临时表,各会话只会读写该会话内创建的本地临时表
    • 本地临时表的数据对会话内的所有事务可见
    • 在会话结束后,该会话创建的本地临时表会被自动删除
    • 本地临时表可以与普通表同名,此时在 DDL 和 DML 语句中,普通表被隐藏,直到本地临时表被删除

• 用户可通过 CREATE TEMPORARY TABLE 语句创建本地临时表,通过 DROP TABLE 或 DROP TEMPORARY TABLE 语句删除本地临时表。

tidb> create table test.temp1 (id int);
Query OK, 0 rows affected (0.51 sec)

tidb> create temporary table test.temp1 (name char(10));
Query OK, 0 rows affected (0.00 sec)

tidb> desc test.temp1;
+-------+----------+------+------+---------+-------+
| Field | Type     | Null | Key  | Default | Extra |
+-------+----------+------+------+---------+-------+
| name  | char(10) | YES  |      | NULL    |       |
+-------+----------+------+------+---------+-------+
1 row in set (0.00 sec)

tidb> drop table test.temp1;
Query OK, 0 rows affected (0.00 sec)

tidb> desc test.temp1;
+-------+---------+------+------+---------+-------+
| Field | Type    | Null | Key  | Default | Extra |
+-------+---------+------+------+---------+-------+
| id    | int(11) | YES  |      | NULL    |       |
+-------+---------+------+------+---------+-------+
1 row in set (0.00 sec)

猜你喜欢

转载自blog.csdn.net/wangzhicheng987/article/details/130776850