假设我有这两个表:
|Customers | |Purchases |
---------------- -----------------
|CusID |----- |PurchaseID |
|CusName | |---<|CusID |
|CusAge | |ItemName |
|CusDateAdded | |DatePurchased |
我需要通过多个ItemNames过滤我的结果集。假设我想要退回购买“相机”和“手机”的所有年龄在18到24岁之间的客户。我可以运行以下查询来获取年龄范围之间的客户的所有记录:
SELECT CusID
FROM Customers AS C
JOIN Purchases AS P
ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
但是,当需要过滤购买表中的ItemName列时,如何在多行上进行过滤?假设没有多个查询可以吗?
答案 0 :(得分:2)
SELECT C.CusID
FROM Customers AS C
JOIN Purchases AS P ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
AND ItemName IN ('camera','phone')
GROUP BY C.CusID
HAVING count(distinct ItemName) = 2
由客户分组并仅返回具有这两项的人。
答案 1 :(得分:0)
我相信这会回答您的问题: SQL FIDDLE
SELECT C.CustID,C.CustName,P.ItemName
FROM Customers AS C
JOIN Purchases AS P ON C.CustID = P.CustID
GROUP BY C.CustID,C.CustName,P.ItemName
HAVING P.ItemName IN ('camera','phone')