简体   繁体   English

创建和使用临时表

[英]Creating and using temporary tables

I have just learnt about temporary tables and using them has given me some really nice speed increases in some of my big queries. 我刚刚了解了临时表,使用它们在我的一些大查询中给了我一些非常不错的速度提高。

The problem I have is that when I create the table, it doesn't last for the full length of the following query that uses it nor until the end of the script. 我遇到的问题是,在创建表时,它不会持续到使用该表的以下查询的整个长度,也不会持续到脚本结尾。

I am creating it using: 我正在使用创建它:

$dbh->exec("CREATE TEMPORARY TABLE _temp_unique_invoice_ref ENGINE = MEMORY AS
        (SELECT jobRef, invoiceRef FROM invoices_out_reference GROUP BY invoiceRef)") ;

The query after it is a few hundred lines long and tries to make use of the temporary table many times in subqueries, but it only works for the first subquery and the rest of the query fails saying that the table does not exist. 它后面的查询有几百行长,并试图在子查询中多次使用临时表,但它仅适用于第一个子查询,而其余查询则说该表不存在而失败。

The scenario is also further complicated by the fact that this query will be run every 10 seconds potentially by many users, so it could be executed many times before 10 seconds has elapsed. 由于该查询可能每10秒由许多用户运行一次,因此该场景也变得更加复杂,因此可以在10秒过去之前执行多次。

How can I make this work without not using the TEMPORARY keyword and drop etc? 如何在不使用TEMPORARY关键字和drop等的情况下完成这项工作?


The query that follows is just one large query. 接下来的查询只是一个大型查询。 Prepare is called on the same object so could that be causing a new connection? 在同一对象上调用Prepare,是否可能导致新连接? Would it work if I put the create table syntax at the start of the larger query and terminate it with ;? 如果我将create table语法放在较大查询的开头,并以;终止,是否可以?

A temporary table cannot be used several times in one query. 临时表不能在一个查询中多次使用。

If the data is not too large, you could, however, create copies with 如果数据不是太大,则可以使用以下命令创建副本

CREATE TEMPORARY t2 SELECT * FROM t;
CREATE TEMPORARY t3 SELECT * FROM t;
CREATE TEMPORARY t4 SELECT * FROM t;

and use them in the big query. 并在大型查询中使用它们。

There is not enough information about your setup. 有关您的设置的信息不足。 So I try a wild guess: could it be that you are making a fresh connection for each query and the temporary table is bound to a connection, thus does not exist in others ? 因此,我尝试一个大胆的猜测:是否可能是您为每个查询建立了一个新的连接,并且临时表已绑定到一个连接,因此在其他连接中不存在?

You can use :: 您可以使用 ::

Insert into temp_table select from table

It will automatically create a table with the description same as table, and when you are done drop it. 它会自动创建一个描述与表相同的表,完成后将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM