所以我有三张桌子。 CUSTOMER( CustomerID ,LastName,FirstName),PURCHASE( PurchaseID ,ItemName)和TRANSACTION( CustomerID , PurchaseID ,日期)。
我遇到的问题是我需要获得专门购买“Paint”和“Books”两个项目的客户的全名,但是当我运行我的代码时,没有任何问题出现。这就是我所拥有的:
SELECT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER, PURCHASE
WHERE PURCHASE.Item = 'Paint' AND PURCHASE.Item = 'Books'
GROUP BY CUSTOMER.LastName, CUSTOMER.FirstName;
请帮助,我真的很陌生,真的很想帮忙。
答案 0 :(得分:5)
此类问题称为Relational Division
。
SELECT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER
INNER JOIN TRANSACTION
ON CUSTOMER.CustomerID = TRANSACTION.CustomerID
INNER JOIN PURCHASE
ON TRANSACTION.PurchaseID = PURCHASE.PurchaseID
WHERE PURCHASE.Item IN ('Paint', 'Books') -- list all items here
GROUP BY CUSTOMER.LastName, CUSTOMER.FirstName
HAVING COUNT(DISTINCT PURCHASE.Item) = 2 -- the total number of items searched
如果在每笔交易中对每个UNIQUE
强制执行ItemName
约束,您可以使用*
SELECT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER
INNER JOIN TRANSACTION
ON CUSTOMER.CustomerID = TRANSACTION.CustomerID
INNER JOIN PURCHASE
ON TRANSACTION.PurchaseID = PURCHASE.PurchaseID
WHERE PURCHASE.Item IN ('Paint', 'Books')
GROUP BY CUSTOMER.LastName, CUSTOMER.FirstName
HAVING COUNT(*) = 2
答案 1 :(得分:1)
没有连接..
SELECT DISTINCT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER A
JOIN TRANSACTION B
ON A.CUSTOMERID=B.CUSTOMERID
JOIN PURCHASE C
ON B.PURCHASEID=C.PURCHASEID AND C.ITEM='Paint'
JOIN PURCHASE D
ON B.PURCHASEID=D.PURCHASEID AND D.C.Item = 'Books'
答案 2 :(得分:0)
您需要JOIN
个表格。尝试
SELECT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER
INNER JOIN TRANSACTION ON TRANSACTION.CustomerID=CUSTOMER.CustomerID
INNER JOIN PURCHASE ON PURCHASE.PurchaseID=TRANSACTION.PurchaseID
WHERE PURCHASE.Item = 'Paint' OR PURCHASE.Item = 'Books'
GROUP BY CUSTOMER.LastName, CUSTOMER.FirstName
HAVING COUNT(DISTINCT PURCHASE.Item) >= 2;
答案 3 :(得分:0)
SELECT CUSTOMER.FirstName, CUSTOMER.LastName
FROM CUSTOMER C, PURCHASE P, TRANSACTION T
WHERE
C.CUSTOMERID = T.CUSTOMERID AND T.PurchaseID = P.PurchaseID
AND P.Item IN ('Paint','Books')
这是伪代码。亲自尝试一下。