Search code examples
mysqlsqljooq

How to write LEFT OUTER JOIN on the same table in 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


Solution

  • Maybe

    SELECT *
    FROM food_db_schema.tblCategory AS t1
    WHERE t1.category_id IS NULL
    AND t1.heartbeat = "ALIVE";
    

    , but are you sure t2.parent_id is both supposed to be NULL and equal to t1.category_id?

    EDIT:

    Then something like

    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"));
    

    depending on what the generated classes, properties and meta-model objects are called.