I use this code for select count of posts
$select = SELECT COUNT( DISTINCT wpPost.ID )
FROM `wp_posts` wpPost
RIGHT JOIN `wp_woocommerce_order_itemmeta` wpOrderItem
ON wpOrderItem.`meta_value`='6246'
WHERE wpPost.`post_status`='wc-completed'
GROUP BY wpPost.`ID`
ORDER BY wpPost.`post_date` DESC
$wpdb->get_results("$select");
echo $wpdb->num_rows;
But this code is very slow and long time about 40 sec!
wp_woocommerce_order_itemmeta
have 388116 records
One reason DISTINCT should be used only when absolutely necessary is that the result set must be sorted in order to find and remove duplicates
I am not sure why your query is taking a long time, but I have one workaround, sum count by removing distinct from query.
Arbitrarily choosing to keep the minimum ID. Also, avoid using the implicit join syntax.
Your Query should be:
SELECT COUNT( wpPost.ID ), MIN( wpPost.ID)
FROM `wp_posts` wpPost
RIGHT JOIN `wp_woocommerce_order_itemmeta` wpOrderItem
ON wpOrderItem.`meta_value`='6246'
WHERE wpPost.`post_status`='wc-completed'
GROUP BY wpPost.`ID`
ORDER BY wpPost.`post_date` DESC
I would start with adding the following indexes to optimize this query:
ALTER TABLE
`wp_posts`
ADD
INDEX `wp_posts_index_1` (`post_status`, `ID`);
ALTER TABLE
`wp_woocommerce_order_itemmeta`
ADD
INDEX `wp_woocommerce_order_itemmeta_index_1` (`meta_value`);
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.