0

I have following SQL that is doing what I want (simplified):

SELECT tcd.Name, MAX(if(tcd.Name = 'Some Name', tcr.Value, NULL)) as 'Value'
FROM TestCaseData tcd, TestCaseDataResult tcr, PVRTable pvr,
(select MAX(sel.PK) as PK from TestCaseDataResult sel GROUP BY sel.PVR_FK, sel.TCD_FK) selector
WHERE tcr.PK = selector.PK AND tcr.TCD_FK = tcd.PK AND tcr.PVR_PK = pvr.PK
GROUP BY pvr.PK
ORDER BY pvr.PK

Selector table is needed because the set can have several records with the same sel.PVR_FK, sel.TCD_FK, and in that case the MAX(...) expression will select the bigger value, but I need to have the value with bigger PK instead (last value)

I want to have HQL instead of SQL. I'm trying to avoid using raw SQL in the code for the obvious reasons.

Looks like HQL does not support subqueries in the FROM. I feel like I can rewrite this so it could work without subquery but with self-join, but I'm struggling to find a correct solution.

I am also quite worried about the performance, so I do not want to have subqueries in SELECT due to inefficiency.

1 Answer 1

1

I believe u can try this

SELECT tcd.Name, MAX(if(tcd.Name = 'Some Name', tcr.Value, NULL)) as 'Value')
FROM TestCaseData tcd, TestCaseDataResult tcr, PVRTable pvr
WHERE 
    tcr.PK IN(select MAX(PK) from TestCaseDataResult GROUP BY PVR_FK, TCD_FK) 
    AND tcr.TCD_FK = tcd.PK 
    AND tcr.PVR_PK = pvr.PK
GROUP BY pvr.PK
ORDER BY pvr.PK

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-subqueries

Sign up to request clarification or add additional context in comments.

2 Comments

Will select MAX(tcr.PK) as PK from TestCaseDataResult sel GROUP BY sel.PVR_FK, sel.TCD_FK be executed N times in case of this? I'm trying to avoid this
answer updated. Nope. It have no relation to other tables and in join-context it will be some kind of static. sorry for English

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.