跳轉到

善用 Temporary Table 寫報表

  • 所有寫進 Temporary table 的資料在 Connection Close / TX commit 時都會被刪除
  • 所以不會使用正常的 table space ,速度比一般 table 更快
  • Temporary table 是每個 Connection 專屬的,不會互相干涉
  • 所以不會有 locking/blocking ,速度很快的
  • 如果你的 SQL 太長,可以考慮把 SQL 變成數個 statement ,然後把中間的結果放進 Temporary table 內

案例 1

想更新多筆資料的 socre 欄位 ,id = 1 的 改成 60, id = 2 的 改成 70, id = 3 的改成 80

create temporary table tempTable (
  id int,
  score int
);

insert into tempTable (id, score) values
(1, 60), (2, 70), (3, 80);

update myTable set score = tempTable.score
from tempTable
where myTable.id = tempTable.id;

案例 2

如果想從 Table1 拿 colX = 'A' or 'C' or 'E' 的資料

select * from Table1
where colX in ('A', 'C', 'E');

如果想從 Table1 拿 colX = 'A' or 'C' or 'E' or...... (超過 1000 個值)

create temporary table tempTable (
  colX char(1)
);

insert into tempTable (colX) values
('A'), ('C'), ('E')......

select * from Table1
inner join tempTable
on Table1.colX = tempTable.colX;