我正在尝试获取订单中A类商品的所有订单,但B类商品也不在订单上。不幸的是,表格结构存在一些缺陷,这使得这比我想象的要困难一些。
数据库问题:
- 没有“订单”表,只有“Order_Lines”表。但是,我可以假设任何具有相同“OrderDate”字段和相同客户(见下文)的Order_Lines都是同一订单的一部分。
- 为每个交易创建一个新的“客户”记录(yikes!),因此“CustID”字段无用。但是,我可以假设具有相同“FirstName”和“LastName”的任何客户都是相同的。
数据库布局:
Order_Lines:
OrderLineID CustID ProductID OrderDate
----------- ----- ----------- ----------
10 5 50 2011-08-01
20 6 60 2011-08-01
30 7 50 2011-08-02
40 8 55 2011-08-03
50 9 70 2011-08-03
Customer:
CustID FirstName LastName
----- --------- ---------
5 Bill Smith
6 Bill Smith
7 Roger Wilcock
8 Rudiger Fensterbottom
9 Sam Williams
ProductTypes:
ProductID ProductType
--------- -----------
50 Kite
55 Kite
60 Yo-Yo
70 Yo-Yo
我想获得订购风筝的所有订单,但Yo-Yos订单不同。在这种情况下我的结果集是:
ProductID OrderDate FirstName LastName
--------- --------- --------- --------
50 2011-08-02 Roger Wilcock
55 2011-08-03 Rudiger Fensterbottom
答案 0 :(得分:1)
这是基础知识。我跟Exists
一起去。我的目的是展示一个概念,而不是为您编写完整的代码。
Select
*
From
OrderLines as OL
Where
Exists (Select * from OrderLines as OL2 where OL2.ProductID = 50 and OL2.PatID = OL.PatID and OL2.OrderDate = OL.OrderDate) -- Has ProductID: 50
and NOT Exists (Select * from OrderLines as OL3 where OL3.ProductID = 60 and OL3.PatID = OL.PatID and OL3.OrderDate = OL.OrderDate) -- Does not have ProductID: 60
答案 1 :(得分:1)
SELECT
OL1.*
FROM
Order_Lines OL1
INNER JOIN Product_Types PT1 ON
PT1.product_id = OL1.product_id AND
PT1.product_type = 'Kite'
INNER JOIN Customers C1 ON
C1.customer_id = OL1.customer_id
WHERE
NOT EXISTS (
SELECT *
FROM Order_Lines OL2
INNER JOIN Product_Types PT2 ON
PT2.product_id = OL2.product_id
INNER JOIN Customers C2 ON
C2.customer_id = Order_Lines.customer_id AND
C2.first_name = C1.first_name AND
C2.last_name = C1.last_name
WHERE
OL2.order_date = OL1.order_date AND
PT2.product_type = 'Yo-Yo')