title: Creating and using temporary tables
body: <p>I have just learnt about temporary tables and using them has given me some really nice speed increases in some of my big queries.</p>
  
  <p>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.</p>
  
  <p>I am creating it using:</p>
  
  <pre><code>$dbh-&gt;exec("CREATE TEMPORARY TABLE _temp_unique_invoice_ref ENGINE = MEMORY AS
          (SELECT jobRef, invoiceRef FROM invoices_out_reference GROUP BY invoiceRef)") ;
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>How can I make this work without not using the TEMPORARY keyword and drop etc?</p>
  
  <hr>
  
  <p>The query that follows is just one large query. Prepare is called on the same object so could that be causing a new connection? Would it work if I put the create table syntax at the start of the larger query and terminate it with ;?</p>