我正在尝试编写一个查询,该查询将返回仅包含订阅的所有订单。编写包含所有订阅订单的查询很容易,另一个订单包括没有订阅的所有订单,然后将它们与不匹配的查询进行比较。
但是我不想在我的Access数据库中存储查询,我更喜欢在我的ASP代码中使用它,并且我不能只使用一个复杂的查询。
以下是我存储时的效果示例:
Query1
SELECT tblOrders.OrderID, tblOrderItems.ProductID
FROM tblOrders INNER JOIN tblOrderItems ON tblOrders.OrderID = tblOrderItems.OrderID
WHERE ((Not ((tblOrderItems.ProductID)>=12 And (tblOrderItems.ProductID)<=15)));
Query2
SELECT tblOrders.OrderID, tblOrderItems.ProductID
FROM tblOrders INNER JOIN tblOrderItems ON tblOrders.OrderID = tblOrderItems.OrderID
WHERE ((((tblOrderItems.ProductID)>=12 And (tblOrderItems.ProductID)<=15)));
Query3
SELECT Query2.OrderID, Query2.ProductID
FROM Query2 LEFT JOIN Query1 ON Query2.OrderID = Query1.OrderID
WHERE (((Query1.OrderID) Is Null));
所以,我的问题是'如何编写Query3,以便它不引用Query1或Query2?' 或者,我是否缺少其他方式呢?
谢谢, 皮特 peteaugello@verizon.net
答案 0 :(得分:2)
假设
这样的事情怎么样:
SELECT O.OrderID, TOI.ProductID
FROM tblOrders O
INNER JOIN tblOrderItems TOI ON (O.OrderID = TOI.OrderID)
WHERE (TOI.ProductID between 12 and 15) AND
NOT EXISTS (SELECT *
FROM tblOrderItems TOI2
WHERE (NOT TOI2.ProductID between 12 and 15) AND
(TOI2.OrderID=O.OrderID)
)
答案 1 :(得分:0)
如果您不想担心加入,可以使用数据透视表进行此操作。
select OrderID,
sum(case productID between 12 and 15 then 1 else 0 end) HAS_SUBSCRIPTION,
sum(case productID between 12 and 15 then 0 else 1 end) HAS_OTHER
FROM tblOrderItems
GROUP BY OrderID
HAVING HAS_SUBSCRIPTION > 0 and HAS_OTHER = 0;