是否有更方便更簡單的方法來編寫下列SQL代碼?SQL嵌套子查詢與計數
SELECT
products.name,
(SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'debt') AS debt,
(SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'cash') AS cash,
(SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'free') AS free
FROM `sales`, `products`
WHERE `sales`.`product_id` = `products`.`id`
GROUP BY `products`.`id`
我可以添加另一個JOIN語句? '在S.time <= mytime上加入S' –
應該將其作爲'WHERE'子句添加,而不是'JOIN'語句。 – Siyual
您可能還想添加條件:'where S.Payment_method in('debt','cash','free'')。這不會改變結果,但可以提高性能。 –