I have a JPAQL-2-mySQL query that stops running after 5 minutes by timeout:
select
question,
ans_items,
count(distinct ans_items.id) as voteCount,
(select
count(distinct ans.id)
from
answers ans
join ans.session ses
where
ses.survey.id = :surveyId
and ses.state = :sessionState
and ans.question.id = question.id
group by
question.id) as total,
max(ranks.rank) as rmax
from
Session as ss
join ss.answers as answers
join answers.items as ans_items
join answers.question as question
left join question.ranks as ranks
where
ss.survey.id = :surveyId
and ss.state = :sessionState
group by
question.id,
ans_items.variant.id,
ans_items.variantWeight
order by
question.orderNumber asc
If I replace COUNTs with constant values:
select question, ans_items, 150,
(select 10 from answers ans join ans.session ses
where ses.survey.id=:surveyId and ses.state=:sessionState
and ans.question.id=question.id group by question.id) as total,
max(ranks.rank) as rmax
from Session as ss
join ss.answers as answers
join answers.items as ans_items
join answers.question as question
left join question.ranks as ranks
where ss.survey.id=:surveyId and ss.state=:sessionState
group by question.id, ans_items.variant.id, ans_items.variantWeight
order by question.orderNumber asc
, it starts being executed in 2 seconds. Which is 150+ times faster. It seems like a couple of COUNTs slow down the query a lot! Is there a way to optimize the query or I absolutely have to calculate counts not using the DB (I can do this, but I'd like to avoid such kind of rewriting).