I have a query where I'm trying to do a COUNT and a SUM with a LEFT JOIN. The LEFT JOIN is adding it's results to total count. I'm sure this is the nature of doing a LEFT JOIN. But, I would like to know is there a way around this? Or, do I need to run a separate query to get accurate results? The SUM returns normal.
What I'm trying to do is get the number of orders for each month for whatever year that is being accessed.
$query1 = "SELECT orderinfo_date, (SELECT COUNT(*) FROM orderinfo WHERE WHERE date_format(`orderinfo_date`, '%Y') = '$yearId') AS monthTotal, ROUND(SUM(orderitems_price * orderitems_quantity), 2) AS monthSum
FROM orderinfo
LEFT JOIN orderitems ON orderinfo.orderinfo_id = orderitems.orderitems_oid
WHERE date_format(`orderinfo_date`, '%Y') = '$yearId'
GROUP BY date_format(`orderinfo_date`, '%m')";
$result1 = mysql_query($query1);
On a side note, I have another query that does the same thing. But, this one works fine. It has one additional WHERE clause. The month is being supplied to the query. Where as, the query above does not.
$query1 = "SELECT company_name, company_id, orderinfo_date, (SELECT COUNT(*) FROM orderinfo WHERE orderinfo_coid = company_id AND date_format(`orderinfo_date`, '%m') = '$monthId' AND date_format(`orderinfo_date`, '%Y') = '$yearId') AS monthTotal, ROUND(SUM(orderitems_price * orderitems_quantity), 2) AS monthSum
FROM company
LEFT JOIN orderinfo
ON company.company_id = orderinfo.orderinfo_coid
LEFT JOIN orderitems
ON orderinfo.orderinfo_id = orderitems.orderitems_oid
WHERE date_format(`orderinfo_date`, '%m') = '$monthId' AND date_format(`orderinfo_date`, '%Y') = '$yearId'
GROUP BY company_id";
$result1 = mysql_query($query1);
Any insight is appreciated. Thanks.