【问题标题】:Why is a temporary table allowed to be referenced only once?为什么临时表只允许被引用一次?
【发布时间】:2021-07-18 02:23:56
【问题描述】:

多次加入temporary table。收到此错误:

Error Code: 1137. Can't reopen table: 'a'

我用谷歌搜索了它,发现在查询中多次引用相同的temporary table 存在某种限制。谁能解释为什么存在这个限制?

下面是一个会导致此错误的简单查询示例:

CREATE TEMPORARY TABLE foo
SELECT * FROM shopify_us limit 10;

SELECT *
FROM (
SELECT *
FROM shopify_us
LIMIT 10
) boo
LEFT JOIN foo a ON a.customer_id = boo.customer_id
LEFT JOIN foo b on b.customer_id = boo.customer_id

但是,如果我只是删除第二个连接,我将不再遇到错误。

【问题讨论】:

  • 我不熟悉这样的错误。也许你应该向他展示查询。
  • 这能回答你的问题吗? Getting around MySQL "Can't reopen table" error
  • @devlincarnate 我阅读了该线程并找到了不同的解决方法,但我的问题仍然存在。我不明白这个限制。

标签: mysql sql


【解决方案1】:

限制是您不能在同一查询中多次引用临时表。例如,不能对临时表进行自联接。但是您可以通过多个后续查询来使用临时表。

这是 MySQL 服务器代码中解释原因的注释,就在引发此错误之前:

/*
  We're trying to use the same temporary table twice in a query.
  Right now we don't support this because a temporary table is always
  represented by only one TABLE object in THD, and it can not be
  cloned. Emit an error for an unsupported behaviour.
*/

https://github.com/mysql/mysql-server/blob/8.0/sql/sql_base.cc#L7284-L7289

THD 指的是会话范围信息的数据结构。临时表的范围仅限于创建它们的会话。它们不是对可以由多个会话共享的表的引用。

换句话说,这只是代码中关于跟踪临时表的数据结构的限制。

另请参阅可追溯到 2005 年的错误报告的历史:https://bugs.mysql.com/bug.php?id=10327

在 MySQL 8.0 中有一个解决方法:您可以使用一个通用表表达式来代替,用于某些类型的用途,而这些用途您会使用临时表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 2012-09-18
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多