Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting SQL with subselect in select to HQL

I have the following SQL that I am having problems converting to HQL. A NPE is getting thrown -- which I think has something to do with the SUM function. Also, I'd like to sort on the subselect alias -- is this possible?

SQL (subselect):

SELECT q.title, q.author_id, 
    (SELECT IFNULL(SUM(IF(vote_up=true,1,-1)), 0) 
    FROM vote WHERE question_id = q.id) AS votecount
FROM question q ORDER BY votecount DESC

HQL (not working)

SELECT q, 
    (SELECT COALESCE(SUM(IF(v.voteUp=true,1,-1)), 0) 
    FROM Vote v WHERE v.question = q) AS votecount
    FROM Question AS q
    LEFT JOIN q.author u
    LEFT JOIN u.blockedUsers ub
    WHERE q.dateCreated BETWEEN :week AND :now
    AND u.id NOT IN (
        SELECT ub.blocked FROM UserBlock AS ub WHERE ub.blocker = :loggedInUser
    )
    AND (u.blockedUsers IS EMPTY OR ub.blocked != :loggedInUser) 
    ORDER BY votecount DESC
like image 483
RyanLynch Avatar asked Apr 30 '10 18:04

RyanLynch


Video Answer


1 Answers

Here is the working HQL if anyone is interested:

SELECT q, 
(SELECT COALESCE(SUM(CASE v.voteUp WHEN true THEN 1 ELSE -1 END), 0) 
FROM Vote v WHERE v.question = q) AS votecount
FROM Question AS q
LEFT JOIN q.author u
LEFT JOIN u.blockedUsers ub
WHERE q.dateCreated BETWEEN :week AND :now
AND u.id NOT IN (
    SELECT ub.blocked FROM UserBlock AS ub WHERE ub.blocker =:loggedInUser
)
AND (u.blockedUsers IS EMPTY OR ub.blocked !=:loggedInUser) 
ORDER BY col_1_0_ DESC

Notice the ORDER BY col_1_0_

There is an open issue with Hibernate -- it does not correctly parse aliases and since the aliases are renamed in the query, an error will be thrown. So, col_1_0_ is basically a workaround --it's the name Hibernate generates. See issue: http://opensource.atlassian.com/projects/hibernate/browse/HHH-892

like image 135
RyanLynch Avatar answered Sep 22 '22 02:09

RyanLynch