如何使用 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";
数据库是 mySQL
flesk 的回答很好地描述了如何使用 jOOQ 1.x 完成此操作。使用别名的自连接或多或少等同于使用别名的常规连接,如手册中所述:
https://www.jooq.org/doc/latest/manual/sql-building/table-expressions/aliased-tables/
在即将到来的 2.0 版本中,别名将变得不那么冗长,并且更加类型安全。因此 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"));
我还在这里描述了一个更复杂的自加入示例:
http://blog.jooq.org/jooq-meta-a-hard-core-sql-proof-of-concept/
也许
SELECT *
FROM food_db_schema.tblCategory AS t1
WHERE t1.category_id IS NULL
AND t1.heartbeat = "ALIVE";
,但你确定t2.parent_id
都应该是 NULL 和等于t1.category_id
?
编辑:
然后像
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"));
取决于生成的类、属性和元模型对象的名称。