Background:
- I'm running a query which gets the total widgets, sprockets, and gizmos ordered by the customer during the last month
- I also have a Total Orders column which runs a subquery counting every order in that month
- The reason I do Total Orders in a subquery, instead of just adding the three columns, is because I also have a further two Total Orders columns for the two previous months
- I have an orders table that stores financial records, and separate tables for actual product details for widgets, sprockets, and gizmos
The problem:
- Occasionally, a widget might be 'half-deleted' (don't ask!) - where it has an orders record, but not a corresponding widgets record
- I do not want to count this in the Total Widgets column - which is easy enough, as I just do a
JOIN
- However, I also do not want to count this in the Total Orders column...
My current query looks like this for Total Widgets:
SELECT
COUNT(orders.id)
FROM orders
JOIN widgets ON widgets.id = orders.item_id
WHERE orders.product_id = 1 -- Product ID 1 is a Widget
AND orders.date BETWEEN "2014-09-01 00:00:00" AND "2014-09-30 23:59:59"
So this will get all 'accurate' widgets, with an intact widget
table record.
Here is my current query for Total Orders:
SELECT
COUNT(orders.id) AS count
FROM orders
JOIN widgets ON widgets.id = orders.item_id AND orders.product_id = 1
WHERE orders.date BETWEEN "2014-09-01 00:00:00" AND "2014-09-30 23:59:59"
So my thinking is that the above query should only JOIN
when the order has a product_id
of 1. However, it JOIN
s in every case. Which means if we've ordered 10 widgets (2 of which have been half-deleted), 5 sprockets, and 5 gizmos, rather than showing 18 orders, it only shows 8. Changing to a LEFT JOIN
shows 20, which is still wrong, it should be 18.
Hopefully the above makes sense - thanks in advance.