简体   繁体   中英

Hibernate HQL LEFT JOIN not performing same as equivalent SQL

Cannot work out why these two statements return a different number of results. They should be the same. The SQL version (correctly) returns 2 results and the HQL version returns (incorrectly) 3 results.

The output of the SQL returns 3 results of tb2.user with values 1, null and null. The where clause means this filters down to 2 results, removing the result with a tb2.user value of 1. However, the HQL version returns 3 results. I would like the HQL to return 2 results.

My SQL

SELECT * FROM table1 as tb1 LEFT JOIN table2 as tb2 ON tb1.user = tb2.blocked WHERE tb2.user <> 1 OR tb2.user is null;

My HQL

SELECT r FROM table1 tb1 LEFT JOIN table2 tb2 ON tb1.user.id = tb2.user.id WHERE tb2.user.id <> :userId OR tb2.user.id is null GROUP BY tb1

Any help on this is much appreciated!

You should not use left joined table's column in where condition .. this work as an inner join
you should move these condition in the related ON clause

and in the second query ( My HQL) you have an improper group by without aggregation function (so the query are not equivalent) (when you need distinct result .. use Distinct clause )

  SELECT r 
  FROM table1 tb1 
  LEFT JOIN table2 tb2 ON tb1.user.id = tb2.user.id 
    AND  ( tb2.user.id <> :userId OR tb2.user.id is null ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM