'Slow Query in WooCommerce, what to do?
I have written a Plugin that displays the sum of all purchases of all customers of the last year, ordered by the sum (Customer who bought the most is on top). It is run via cronjob once a day and sends a mail. But now if fails more and more often.
I am sure that my solution was ok for a smaller shop with not a lot of customers and orders, but now the shop has grown, and it has to be rewritten.
I am doing this by creating a Temp(orary) Table and then filling it with all order and customer data I need. Later I query this Temp Table to get the results I need.
The first query is this:
SELECT pm.meta_value AS user_id, pm.post_id AS order_id
FROM ".$wpdb->prefix."postmeta AS pm
LEFT JOIN ".$wpdb->prefix."posts AS p
ON pm.post_id = p.ID
WHERE p.post_type = 'shop_order'
AND p.post_date >= '".$one_year_back."'
AND p.post_status = 'wc-completed'
AND pm.meta_key = '_customer_user'
ORDER BY pm.meta_value ASC, pm.post_id DESC
Then I do
foreach($query as $result) {
$query_firstname = $wpdb->get_row("SELECT meta_value
FROM ".$wpdb->prefix."usermeta
WHERE user_id = ".$result->user_id."
AND meta_key = 'first_name'");
...and 5 other similar queries...
}
I know it's not the best idea to run queries inside of queries, but I failed to do this differently. When I measure the runtime for different parts of my script I can see that the problem lies here.
So I thought of 2 possibilities:
1.) Change the SQL structure to one big query.
2.) Creating a permanent lookup Table (instead of always recreating the Temp Table) and keep it updated.
For 1.) I failed so far. What would be the better way to do this? For 2.) How should lookup tables be handled? Surely there must be hooks for actions like "Change status of Order to 'Complete'" or "Revoke Status 'Complete'" etc.
Looking forward to your suggestions :-)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|