I have the following query that I would appreciate any optimization advice. See explanation below.
Code:
select distinct new Map(sp.state as receive)
from Coupling c
join c.statePrevious sp
where (select count(sp0) from c.statePrevious sp0 where sp0.state in (from ReceiveCoupling))=1 and
(select count(sp1) from c.statePrevious sp1 where sp1.state in (from InvoiceCoupling))=0 and
sp.state in (from ReceiveCoupling) and
c.shipment.poCoupling.size=:size and
c.shipment.poCoupling.grade=:grade and
c.shipment.poCoupling.endFinish=:endFinish and
c.contact=:contact
Coupling is a Joined Subclass of GenericItem and is mapped to StatePrevious as @OneToMany(mappedBy="genericItem").
ReceiveCoupling, InvoiceCoupling are Joined subclasses of State.
Every line item of inventory has a list of states that is has been through.
What I want is all ReceiveCoupling that have no InvoiceCoupling in its StatePrevious and has Couplings of the specific type attached.
I would greatly appreciate any help as this query runs unacceptably slow and there is a minute percentage of data currently in the database.