[英]How to write LEFT OUTER JOIN on the same table in 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";
數據庫是mySQL
flesk的回答很好地描述了如何使用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/
也許
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"));
取決於生成的類,屬性和元模型對象的調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.