简体   繁体   中英

MySQLi Temporary Tables With PHP

I want to ask if this approach will work. I have an enormous table called earnings that I often have to query.

I'm trying to optimize so that I only query according to the relevant campaign_id. I need to complete queries faster!

What I think may be the solution is to create a temporary table near the top of my PHP file, and then drop the temporary table at the end.

Between that I should be able to run more intensive queries on the temporary table because it has a much more limited data set.

I'm a bit scared about using this approach.

  1. Is my general thinking about this approach right?
  2. Have I written these queries and PHP correctly?
  3. Will these tables be dropped correctly? I'm a bit concerned about temporary tables hanging around and crashing or even fatally stalling my instance.

     //Create temporary table for the campaign_id $query = "CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp AS (SELECT * FROM earnings WHERE earning_paid_campaign_id = ? OR earning_free_campaign_id = ?)"; if ($statement = $mysqli->prepare($query)) { $statement->bind_param("ii", $campaign_id, $campaign_id); $statement->execute(); $statement->close(); } ....VARIOUS QUERIES ON earnings_temp..... //Drop temporary table for campaign_id $query = "DROP TEMPORARY TABLE IF EXISTS earnings_temp"; if ($statement = $mysqli->prepare($query)) { $statement->execute(); $statement->close(); } 
  1. You are right. Making temporary tables can help to optimize your workflow on certain cases. Mostly when handling large data sets (like the one you propose).

  2. Your PHP seems correct. You create it, then you dispose it.

  3. Don't worry about having tables hanging around and crashing or even fatally stalling my instance, since they are dropped automatically when the connection is cut. But beware, if tables get too big they end up moving from a memory type to a on-disk table, reducing its speed. Also if there is too many concurrent connections and you don't have enought memory it could stall the DB. But a proper config of the server can avoid that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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