Question

I have to show the orders which contains at least three products from the same producer But it returns all the order codes and not those i ask for. Apparently my code is wrong. Any ideas how to fix it? Should i try something different than having count?

create view Orders as
select order_code, Consists.product_code, Offer.producer_code
from Consists, Producers, Offer, Product
where Consists.product_code = Product.product_code 
      and Product.product_code = Offer.product_code 
      and Offer.producer_code = Producers.producer_code


select order_code
from Order_a
where exists   (select Orders.order_code, Orders.producer_code
        from Orders, Offer
            where Orders.product_code = Offer.product_code 
                and Orders.producer_code = Offer.producer_code
        group by Orders.producer_code, Orders.product_code
        having count(Offer.product_code) >=3 )
Was it helpful?

Solution

You need to relate the inner query to the outer query. The subquery also need to be fixed to group by the order_code and producer_code:

select order_code
from Order_a
where order_code in (select Orders.order_code
                     from Orders join
                          Offer
                          on Orders.product_code = Offer.product_code and
                             Orders.producer_code = Offer.producer_code
                     group by Orders.order_code, Orders.producer_code
                     having count(Offer.product_code) >=3
                    );

I also wonder if the condition should be having count(distinct offer.product_code) >= 3).

Your query is returning all rows because the subquery always produces results, so the exists is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top