简体   繁体   中英

SQL Query to find Woocommerce products that have not sold

I am trying to set up a query that will find products that havn't sold within a time frame and a count. For example I want to find all products within the last year that have sold less than 50 times. I am not sure what is wrong with my query but here it is:

SELECT * FROM `wp_posts` t1 
  INNER JOIN `wp_woocommerce_downloadable_product_permissions` t2 
    ON t1.ID = t2.product_id 
  WHERE t2.access_granted >= "2016-04-30 00:00:00" 
  HAVING COUNT(t2.product_id) <= 50;

The result is always empty even though I know that there are products that have sold less than 50 times within the last year.

Result is empty because you are using Having clause without group by which will count all the rows in the table.
I am assuming your table contains more than 50 rows hence the result will always be empty as count(t2.product_id) will always be > 50.

Try this:

SELECT t2.product_id
FROM `wp_posts` t1 INNER JOIN `wp_woocommerce_downloadable_product_permissions` t2 ON t1.ID = t2.product_id 
WHERE t2.access_granted >= "2016-04-30 00:00:00" 
group by t2.product_id
HAVING COUNT(t2.product_id) <= 50;

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