尝试查询此消息时,我有些卡住: 查找订购了与客户编号250相同的所有客户
数据库架构:
Customers(
customerNumber INTEGER, PRIMARY KEY
);
Orders(
orderNumber INTEGER, PRIMARY KEY
customerNumber INTEGER NOT NULL,
FOREIGN KEY (customerNumber) REFERENCES Customers
);
OrderDetails (
orderNumber INTEGER NOT NULL,
productCode TEXT NOT NULL,
PRIMARY KEY (orderNumber, productCode),
FOREIGN KEY (productCode) REFERENCES Products
);
我想到了这个查询:
select DISTINCT customerNumber
FROM Orders Natural
JOIN OrderDetails
WHERE productCode NOT IN (
select productCode
FROM Orders NATURAL JOIN OrderDetails
WHERE customerNumber = 219
)
order by customerNumber;
将是正确的,但是它什么也不会返回,所以很明显我误会了一些东西。
答案 0 :(得分:0)
当您需要所有客户时,都订购了250个订单或250个以上但具有相同产品的所有产品,因此请尝试使用条件汇总
select customerNumber
FROM Orders o
JOIN OrderDetails od
on o.orderNumber =od.orderNumber
WHERE od.productCode IN (
select productCode
FROM Orders o
JOIN OrderDetails od
on o.orderNumber =od.orderNumber
WHERE customerNumber = 250
)
group by customerNumber
having count(distinct productCode )>=
(select count(distinct productCode )
FROM Orders o
JOIN OrderDetails od
on o.orderNumber =od.orderNumber
WHERE customerNumber = 250)