我正在练习编写SQL查询,我只是想检查一下我的答案是否能给我想要的结果。
我得到了数据库的几个表,我需要检索“已经从堪培拉的供应商订购了任何产品的客户的客户ID”
表格:
我编写的SQL查询:
SELECT Customer.CustomerID
FROM Customers, Orders
WHERE (Customers.CustomerID = Orders.CustomerID)
AND (Orders.ProductID IN (SELECT Products.ProductID
FROM Suppliers, Products
WHERE (Products.SupplierID = Suppliers.SupplierID)
AND (Suppliers.City = 'Canberra'))
查询应检索与曾经订购过堪培拉供应商生产的产品的客户匹配的客户编号列表。
答案 0 :(得分:1)
看起来不错。如果只需要客户数量,则可以只选择COUNT(Customer.CustomerID)
。
答案 1 :(得分:1)
我将SELECT
更改为SELECT DISTINCT
:否则,对于每个与产品条件匹配的订单,您将获得一个CustomerID
行;每个客户可以有多个(订单)。
虽然我将完全按照您的要求编写查询(并添加了DISTINCT
),但您可能会认为以下示例更具可读性:
SELECT
Customer.CustomerID
FROM
Customers,
Orders,
Products,
Suppliers
WHERE
Customers.CustomerID = Orders.CustomerID AND
Orders.ProductID = Products.ProductID AND
Products.SupplierID = Suppliers.SupplierID AND
Suppliers.City = 'Canberra'
GROUP BY
Customer.CustomerID
答案 2 :(得分:1)
使用适当的表联接和别名来做到这一点:
SELECT DISTINCT c.CustomerID
FROM Customers AS c
INNER JOIN Orders AS o ON c.CustomerID = o.CustomerID
INNER JOIN Products AS p ON o.ProductID = p.ProductID
INNER JOIN Suppliers AS s ON p.SupplierID = s.SupplierID
WHERE s.City = 'Canberra'