使用执行查询在左联接子句中添加= value

时间:2018-10-30 10:47:39

标签: java mysql hibernate grails gorm

使用grails 3.3.8和Mysql DB 5.5.x版本。 我已经完成了以下查询:

 String query = $/
            select new Map( i1.id as id,i1.name as name)
            from CustomerComposition as c1
            inner join c1.instrument as i1
            left join i1.analisys as a1,
            Instrument as i2
            left join i2.analisys as a2,
            Instrument as i3
            left join i3.analisys as a3
            where 
            i1.id=i2.id and i1.id=i3.id and
            c1.portfolio.id=:ptfId and a1.phase.id=:p1Id and a2.phase.id=:p2Id and a3.phase.id=:p3Id 
        /$

        List composition = CustomerComposition.executeQuery(query,
                [ptfId: ptfId, p1Id: phase[0], p2Id: phase[1], p3Id: phase[2]])

左联接不起作用。然后我意识到这是行不通的,因为我在WHERE中放置了一个子句。我用简单的SQL语句仔细检查了一下,实际上,一旦将条件移到了哪里,它确实可以工作。一个简单的片段只是为了澄清,之前并没有用:

SELECT
instrument1_.id
FROM
    customer_ptf_composition customerpt0_
    INNER JOIN instrument instrument1_ ON customerpt0_.instrument_id = instrument1_.id
    LEFT JOIN analisys analisys4_ ON instrument1_.id = analisys4_.instrument_id

WHERE
customerpt0_.portfolio_id =1216 
    AND analisys4_.phase_id =111

以及之后,由于左/右联接的工作方式而起作用:

SELECT
instrument1_.id
FROM
    customer_ptf_composition customerpt0_
    INNER JOIN instrument instrument1_ ON customerpt0_.instrument_id = instrument1_.id
    LEFT JOIN analisys analisys4_ ON instrument1_.id = analisys4_.instrument_id AND analisys4_.phase_id =111 

WHERE
customerpt0_.portfolio_id =1216

现在我的问题是如何在GORM的左联接旁边放置“ and field = value”?

1 个答案:

答案 0 :(得分:1)

您可以使用WITH子句来实现:

{{1}}

另请参阅:current Hibernate user guide: HQL explicit join