如何检索每个客户的名称以及他们订购了多少个比萨饼?

时间:2017-09-24 07:19:17

标签: mysql sql

我必须检索每个顾客的名字以及他们订购了多少个比萨饼。如果没有订购比萨饼,则为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

必须更换带编号的空白以产生结果。

1 个答案:

答案 0 :(得分: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`;

如果您还需要每位客户的美元金额,可以轻松添加。