Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOOQ nested condition

Tags:

java

sql

jooq

Hi i am trying to figure out how to write something like this in jooq

select * from table 
where ( ( a = query or b = query or a = query ) 
and ( e = query or g = query or z = query) )

I cant figure out how to do nested condition in jooq. Please help.

like image 421
user1489002 Avatar asked Dec 26 '22 22:12

user1489002


1 Answers

You'll need to understand the following part of the API:

public interface Condition {
    Condition and(Condition other);
    Condition or(Condition other);
}

So any Condition can be connected with other Conditions using and() / or() methods (and others). In your case, you can form your conditions easily like this:

Condition c1 = a.equal(query);
Condition c2 = b.equal(query);
Condition c3 = a.equal(query);

Condition d1 = e.equal(query);
Condition d2 = g.equal(query);
Condition d3 = z.equal(query);

Now these conditions can be connected as such:

c1.or(c2).or(c3).and(d1.or(d2).or(d3));

Or put in a SQL statement:

create.select()
      .from(table)
      .where(c1.or(c2).or(c3)
        .and(d1.or(d2).or(d3)));

Of course, you don't have to assign your c[1-3], d[1-3] conditions to variables. You could inline everything to a single statement:

create.select()
      .from(table)
      .where(a.equal(query).or(b.equal(query)).or(a.equal(query))
        .and(e.equal(query).or(g.equal(query)).or(z.equal(query)));

You'll find more information in the manual:

https://www.jooq.org/doc/latest/manual/sql-building/conditional-expressions/

like image 194
Lukas Eder Avatar answered Jan 09 '23 13:01

Lukas Eder