简体   繁体   中英

HQL query to join table with itself with left outer join

I want to left outer join a table with itself so that I will get additional columns.

I have a table that collect serial number and action as a log. I want join two actions a1 and a2 based on the serial number. The returned result is expected to have serialNumber, a1 and a2. If a2 doesn't exist it will be null. When I use where statement it will only return serialNumber which has both a1 and a2.

"select l.serialNumber, l.time, s.time "
+ "from Log as l left outer join Log as s "
+ "ON s.serialNumber = l.serialNumber "
+ "where s.action = 'a2' AND l.action= 'a1' "
+ "AND l.time >= '" + start.getTime() + "' "
+ "AND l.time <= '" + end.getTime() + "' "

I am getting an exception while trying to run the above query: org.hibernate.TransactionException.

Your HQL is not valid, you don't need (can) specify the JOIN columns, this is already need to be mapped in your entities.

Try:

"select l.serialNumber, l.time, s.time "
+ "left join l.serialNumber s "
+ "where s.action = 'a2' AND l.action= 'a1' "
+ "AND l.time >= '" + start.getTime() + "' "
+ "AND l.time <= '" + end.getTime() + "' "

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