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.