The problem we have is the following. We have a shop_orders database with orders placed by customers:
id | user_id
1 | 1
On the other hand we have the shop_order_products table, which contains the products that each order contains, where the order_id field relates both tables:
id | order_id | qty | product_id | product_name | product_price |
1 | 1 | 2 | 23 | samsung S5 | 40.5
2 | 1 | 1 | 12 | iPhone 6S | 80
Just to clarify, in this example order 1 has 2 units of Samsung and 1 unit of iPhone.
We are able to know, through the shop_order_products table, which are the best selling products of our online store, by calling:
SELECT *, COUNT(*) as sales FROM shop_order_products GROUP BY order_id ORDER BY sales DESC
We need, given a subset of products, to know how many COMPLETE orders we could get. That is, if we had the products that we sell the most are the iPhone 6S and the Samsung Galaxy S5, how many complete orders would we get with those two products. If an order contains both products but also others, it would not be taken into account for our calculation.