how to write following SQL using jOOQ?
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
flesk's answer depicts nicely how this can be done with jOOQ 1.x. A self-join using aliasing is more or less equivalent to a regular join using aliasing as described in the manual:
https://www.jooq.org/doc/latest/manual/sql-building/table-expressions/aliased-tables/
In the upcoming version 2.0, aliasing will be made less verbose and more type-safe. Hence flesk's solution could be simplified as such:
// 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/jooq-meta-a-hard-core-sql-proof-of-concept/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With