I’m writing a query for an application that needs to list all the products with the number of times they have been purchased.
I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM’s, But in this case a query is a much more elegant solution.
Can you spot anything wrong (approach wise) with the query?
SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN ( SELECT * FROM orderitems INNER JOIN orders ON orderitems.order_id = orders.id AND orders.paid = 1 ) AS oi ON oi.product_id = products.id GROUP BY products.id
The schema (with relevant fields) looks like this:
*orders* id, paid *orderitems* order_id, product_id *products* id
UPDATE
This is for MySQL
I’m not sure about the ‘(SELECT *’ … business.
This executes (always a good start) and I think is equivalent to what was posted.