1. 程式人生 > >MySQL 報錯:ERROR 1137 (HY000): Can't reopen table: 'tempId'

MySQL 報錯:ERROR 1137 (HY000): Can't reopen table: 'tempId'

MySQL 報錯:ERROR 1137 (HY000): Can't reopen table: 'tempId'

1. sql 如下

select 
replace(group_concat(distinct tsk.task_name),',' , '\n') as res2
from tempId
join custom_task_rule tsk
  on tsk.task_id = tempId.dependency_job_id
where tempId.dependency_job_id not in (
	select task_id
		from etl_process_log
		where
task_id in( select dependency_job_id from tempId ) and status = 2 and logging_time > '2018-11-30 00:00:00' ); ERROR 1137 (HY000): Can't reopen table: 'tempId'

其中tempId是一個臨時表。
執行如上SQL時,得到的結果是Can't reopen table:'tempId',然後仔細檢查一遍SQL,除了寫的醜了一點兒之外,也沒有別的錯了啊。於是開啟mysql refman手冊。

2. 原因

手冊中關於 temporary table

的介紹如下:

在這裡插入圖片描述其中較為關鍵的提示就是:

You cannot refer to a TEMPORARY table more than once in the same query. For example, the following does not work:
SELECT * FROM temp_table JOIN temp_table AS t2;
The statement produces this error:
ERROR 1137: Can't reopen table: 'temp_table'
The Can’t reopen table error also occurs if you refer to a temporary table multiple times in a stored
function under different aliases, even if the references occur in different statements within the function.
It may occur for temporary tables created outside stored functions and referred to across multiple calling
and callee functions.

在一個查詢中能且僅能引用一次 temporary 表。 上述的那個查詢中將會不work。這個SQL 將會報ERROR 1137: Can't reopen table: 'temp_table'錯誤。
如果你在一個函式中以不同的別名多次引用相同的臨時表,即使在函式不同的語句中引用,這個錯誤同時會出現。對於在儲存函式之外建立的臨時表,但又在多個呼叫和被呼叫函式中引用,也可能會出現這種情況。

3. 解決辦法

所以我們需要修改這個SQL,使其在一個query中只使用到一次tempId表即可