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

Add =value in a left join clause using execute query

使用 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 语句,确实它一旦将条件移出 where 就起作用了。一个简单的截图只是为了澄清,之前它没有用:

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

及之后,由于 left/right join 的工作方式:

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

现在我的问题是如何将 "and field=value" 放在 GORM 的左侧连接旁边?

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

left join i3.analisys a3 WITH a3.something = :someValue

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