I have two queries giving me the same result. Which one is the most efficient?
The model:
Order {
orderId
}
OrderItem {
orderItemId
orderId
productId
}
Product {
productId
}
The relationship between Order and OrderItem is one-to-many, and many OrderItems are related to one Product.
I'd like to retrieve the orders that are related to a specific product (in the requests the parameter :productId).
The first request with inner join:
Select distinct o
from Order o
inner join OrderItem oi
on o.id =
oi.orderId and oi.productId = :productId
The second request with a count subquery in the where clause:
Select o
from Order o
where
(Select count oi
from OrderItem oi
where oi.orderId = o.id and oi.productId = :productId
) > 0
I also use DB2 and Hibernate. And there is an index on each primary and foreign keys.