Subject | Re: Tough sql question |
---|---|
Author | Svein Erling |
Post date | 2003-10-30T09:01:07Z |
--- In firebird-support@yahoogroups.com, "james_027" wrote:
yesterday could be confusing):
any items not in stock (assuming the stock to be ('Apple','Orange',
'Banana')). That means that there should be no OrderItems with any
other value than the stock. We select from Orders and simply use NOT
EXISTS on OrderItems. Here, we have to link to the right order
(oi.order_id = o.id) as well as check for the products we have in
stock. Extending 'stock' to be another table, we could write:
SELECT <Something>
FROM Orders o
WHERE NOT EXISTS(
SELECT * FROM OrderItems oi
WHERE oi.order_id = o.id
AND NOT EXISTS(
SELECT * from stock s
WHERE s.product = oi.Product))
i.e. return all orders that does not contain any orderitem that is not
in stock. Admittedly, the English language is slightly easier than SQL
;o). To list all orders that do contain items not in stock, simply
remove the last NOT. EXISTS can be quite useful whether or not you
prefix it with NOT.
Set
> Hi Svein Erling.The solution James refer to ought to have been (my quick solution
>
> That was a great solution. Do you mind explaining it to me? Iam not
> familiar with the not exist syntax thanks.
yesterday could be confusing):
>SELECT <Something>Well, the task was simply to return all orders that does not contain
>FROM Orders o
>WHERE NOT EXISTS(
>SELECT * FROM OrderItems oi
>WHERE oi.order_id = o.id
>AND oi.Product NOT IN ('Apple','Orange','Banana'))
any items not in stock (assuming the stock to be ('Apple','Orange',
'Banana')). That means that there should be no OrderItems with any
other value than the stock. We select from Orders and simply use NOT
EXISTS on OrderItems. Here, we have to link to the right order
(oi.order_id = o.id) as well as check for the products we have in
stock. Extending 'stock' to be another table, we could write:
SELECT <Something>
FROM Orders o
WHERE NOT EXISTS(
SELECT * FROM OrderItems oi
WHERE oi.order_id = o.id
AND NOT EXISTS(
SELECT * from stock s
WHERE s.product = oi.Product))
i.e. return all orders that does not contain any orderitem that is not
in stock. Admittedly, the English language is slightly easier than SQL
;o). To list all orders that do contain items not in stock, simply
remove the last NOT. EXISTS can be quite useful whether or not you
prefix it with NOT.
Set