我正在做一些SQL语句的例子。 让我们说我有这些表:
会员
MemberID | LastName | FirstName | Birthday | CampusAddress | CampusPhone
FoodItem
FoodItemID | FoodItemName | FoodItemType
_Order
OrderID | MemberID | FoodItemType
订单行
OrderID | FoodItemID | Quantity | Price
我的目标是列出在同一订单上同时订购牛肉(FoodItemID =" 101")和鸡肉(FoodItemID =" 102")的所有会员(memberID,lastname)。
我写了两个声明:
SELECT m.memberid,
m.lastname
FROM member AS m,
_order AS o,
orderline AS ol
WHERE m.memberid = o.memberid
AND o.orderid = ol.orderid
AND ol.fooditemid = '101'
AND ol.fooditemid IN (SELECT ol.fooditemid
FROM member AS m,
_order AS o,
orderline AS ol
WHERE m.memberid = o.memberid
AND o.orderid = ol.orderid
AND ol.fooditemid = '102')
并且
SELECT m.memberid,
m.lastname
FROM member AS m,
_order AS o,
orderline AS ol
WHERE m.memberid = o.memberid
AND o.orderid = ol.orderid
AND ( ol.fooditemid = '101'
OR ol.fooditemid = '102' )
哪一个是对的?
答案 0 :(得分:0)
我会说没有一个是正确的,因为你正在进行隐式连接,这在SQL中已经过时了。
SELECT DISTINCT o.MemberID
FROM Order o
WHERE EXISTS (SELECT 1
FROM OrderItem o1
WHERE o.orderid = o1.orderid AND
o1.fooditemid='101')
AND
EXISTS (SELECT 1
FROM OrderItem o2
WHERE o.orderid = o2.orderid AND
o2.fooditemid='102')
这应该有效,但不确定,如果这是最好的方法。
答案 1 :(得分:0)
您的所有查询都无法满足您的要求。这应该工作:
select distinct Member.LastName,
Member.FirstName,
o1.FoodItemID,
o2.FoodItemID
from _order
inner join _order as o1
on _order.OrderID = o1.OrderID
inner join _order o2
on _order.OrderID = o2.OrderID
inner join Member
on _order.MemberID = Member.MemberID
where o1.FoodItemID = '101'
and o2.FoodItemID = '102'
在这里,您将只获得包含食物项ID并且它们位于投影视图中的订单,以便您可以使用where子句过滤它们。我不知道你是否动态创建了你的查询。