如何使用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
答案 0 :(得分:7)
flesk's answer很好地描述了如何使用jOOQ 1.x完成此操作。使用别名的自联接或多或少等同于使用别名的常规联接,如手册中所述:
http://www.jooq.org/manual/DSL/ALIAS/
在即将发布的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/2011/11/14/jooq-meta-a-hard-core-sql-proof-of-concept/
答案 1 :(得分:5)
也许
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"));
取决于生成的类,属性和元模型对象的调用方式。