Inner join with select on HQL

前端 未结 3 598
野的像风
野的像风 2021-01-03 10:16

I want to do something like that with HQL:

SELECT *
FROM tableA a
INNER JOIN (select fieldA, sum(fieldB) as sum from tableB) b
ON a.fieldA = b.fieldA and a.f         


        
3条回答
  •  我在风中等你
    2021-01-03 10:43

    You can try to do such thing with HQL:

    String sqlText = 
            "select entityA 
             from EntityA entityA, EntityB entityB 
             where entityA.fieldA=entityB.fieldA 
             and entityA.fieldC=(select sum(entityB.fieldB) 
                                 from EntityB entityB 
                                 where entityB.fieldA=entityA.fieldA)"
    
    Query query = session.createQuery(sqlText);
    

    It should work similar to your sql. About your statement - as I know you cannot use inner view in HQL because it is object oriented.

    Here is a good article about joins in HQL.

    EDIT:

    According to notes from user1495181 above query can be rewritten like (but I'm not sure):

    String sqlText = 
            "select entityA 
             from EntityA entityA
             join entityA.entitiesB entityB
             Where entityA.fieldC=(select sum(entityB.fieldB) 
                                 from EntityB entityB 
                                 where entityB.fieldA=entityA.fieldA)"
    

    But I prefer first variant because as for me it is more understandable (especially for peoples who used to work with native SQL).

提交回复
热议问题