2017-09-24 33 views
-2

我必須檢索每個顧客的名字以及他們訂購了多少比薩餅。如果沒有訂購比薩餅,則爲NULL。如何檢索每個顧客的名字以及他們訂購了多少比薩餅?

SELECT blank 1 
FROM blank 2(
SELECT blank 3 AS quantity 
    FROM ORDERS NATURAL JOIN ORDERCONTENTS 
    GROUP BY blank 4) as quantity 
ON customers.customerID=quantity.customerID 
ORDER BY name; 

該數據庫包含在這個佈局5個表:

Customers 
    columns 
     customerID, 
     name, 
     address, 
     phoneNumber, 
     email 

Ordercontents 
    columns 
     orderID, 
     name, 
     quantity 
orders 
    columns 
     orderID, 
     customerID, 
     postcode, 
     Date 

products 
    columns 
     name, 
     price 

stores 
    columns 
     postcode, 
     address, 
     phoneNumber 

編號的空白必須更換產生的結果。

+0

請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

回答

1

應該不需要子查詢/僞表。在三張桌子上使用左連接來獲得答案。

SELECT 
    a.`name`, 
    IF(SUM(b.`quantity`) IS NULL,0,SUM(b.`quantity`)) as `pizzas_ordered` 
FROM Customers a 
LEFT JOIN `orders` o 
ON a.`customerID` = o.`customerID` 
LEFT JOIN `Ordercontents` b 
ON o.`orderID` = b.`orderID` 
GROUP BY a.`customerID` 
ORDER BY a.`name`; 

如果您還需要每個客戶的美元金額,那麼可以很容易地添加。

+0

這只是一個非常複雜的方式說COALESCE(SUM(...),0); – Strawberry

相關問題