JOOQ - 嵌套查询

时间:2014-05-29 18:45:23

标签: java sql jooq

我试图用jooq

编写此查询
SELECT region.*, 
       (SELECT COUNT(*)
        FROM city 
        WHERE city.region_id = region.id) AS num
FROM region;

我尝试了一些事情,但没有成功。到目前为止,我只有

dsl.select().from(Tables.REGION).fetch();

如何在结果中添加num列?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:7)

您的查询将如下所示:

// This is how you can select REGION.*
dsl.select(REGION.fields())

// This is how you can add more fields to the SELECT clause
   .select(

// Nested selects are just select() as well (from DSL)
        select(count())
       .from(CITY)
       .where(CITY.REGION_ID.eq(REGION.ID))

// This is how you convert an org.jooq.Select into a Field
       .asField("num")
   )
   .from(REGION)
   .fetch();

以上实现假设是静态导入:

import static org.jooq.impl.DSL.*;
import static path.to.generated.Tables.*;