Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

jooq

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

like image 287
Charis997 Avatar asked Nov 19 '11 21:11

Charis997


1 Answers

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/

like image 136
Lukas Eder Avatar answered Oct 25 '22 21:10

Lukas Eder