简体   繁体   English

如何在jOOQ中的同一个表上写LEFT OUTER JOIN?

[英]How to write LEFT OUTER JOIN on the same table in jOOQ?

how to write following SQL using jOOQ? 如何使用jOOQ编写以下SQL?

SELECT *
FROM food_db_schema.tblCategory AS t1
LEFT OUTER JOIN food_db_schema.tblCategory AS t2 ON t1.category_id = t2.parent_id
WHERE t2.parent_id IS NULL
AND t1.heartbeat = "ALIVE";

database is mySQL 数据库是mySQL

flesk's answer depicts nicely how this can be done with jOOQ 1.x. flesk的回答很好地描述了如何使用jOOQ 1.x完成此操作。 A self-join using aliasing is more or less equivalent to a regular join using aliasing as described in the manual: 使用别名的自联接或多或少等同于使用别名的常规联接,如手册中所述:

http://www.jooq.org/manual/DSL/ALIAS/ http://www.jooq.org/manual/DSL/ALIAS/

In the upcoming version 2.0, aliasing will be made less verbose and more type-safe. 在即将推出的2.0版本中,别名将更简洁,更安全。 Hence flesk's solution could be simplified as such: 因此,flesk的解决方案可以简化为:

// Type-safe table aliasing:
TblCategory t1 = TBLCATEGORY.as("t1");
TblCategory t2 = TBLCATEGORY.as("t2");

Record record = create.select()
                      .from(t1)
                       // t1 and t2 give access to aliased fields:
                      .leftOuterJoin(t2).on(t1.CATEGORY_ID.equal(t2.PARENT_ID))
                      .where(t2.PARENT_ID.isNull())
                      .and(t1.HEARTBEAT.equal("ALIVE"));

I have also described a more complex example for a self-join here: 我还在这里描述了一个更复杂的自连接示例:

http://blog.jooq.org/2011/11/14/jooq-meta-a-hard-core-sql-proof-of-concept/ http://blog.jooq.org/2011/11/14/jooq-meta-a-hard-core-sql-proof-of-concept/

Maybe 也许

SELECT *
FROM food_db_schema.tblCategory AS t1
WHERE t1.category_id IS NULL
AND t1.heartbeat = "ALIVE";

, but are you sure t2.parent_id is both supposed to be NULL and equal to t1.category_id ? ,但你确定t2.parent_id都应该是NULL并且等于t1.category_id吗?

EDIT: 编辑:

Then something like 然后像

Table<TblCategoryRecord> t1 = TBLCATEGORY.as("t1");
Table<TblCategoryRecord> t2 = TBLCATEGORY.as("t2");

Field<Integer> t1CategoryId = t1.getField(TblCategory.CATEGORY_ID);
Field<String> t1Heartbeat = t1.getField(TblCategory.HEARTBEAT);
Field<Integer> t2ParentId = t2.getField(TblCategory.PARENT_ID);

Record record = create.select().from(t1)
      .leftOuterJoin(t2).on(t1CategoryId.equal(t2ParentId))
      .where(t2ParentId.isNull())
      .and(t1Heartbeat.equal("ALIVE"));

depending on what the generated classes, properties and meta-model objects are called. 取决于生成的类,属性和元模型对象的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM