Build nested condition with SelectQuery object

2019-07-15 13:56发布

问题:

Can I build nested conditions using the SelectQuery object?

I want to get:

select * 
from car 
where ((car.color = 'blue' or car.model = 'Genesis') 
or (car.manufactor = 'ford' and car.color = 'blue'))

回答1:

If you inline all conditions / predicates...

... then you can supply them just like that to your SelectQuery object:

SelectQuery query = ...
query.addConditions( ( CAR.COLOR.eq("blue") .or ( CAR.MODEL.eq("Genesis") ) )
                 .or ( CAR.MANUFACTOR.eq("ford") .and ( CAR.COLOR.eq("blue") ) ) )

I've added some whitespace for improved readability

If you want to perform dynamic query building...

... Then you can create your predicate in various steps:

Condition condition;

condition = CAR.COLOR.eq("blue");
condition = condition.or(CAR.MODEL.eq("Genesis"));
condition = condition.or(CAR.MANUFACTOR.eq("ford").and(CAR.COLOR.eq("blue")));

Both approaches are completely equivalent.



回答2:

I'm looking at the documentation now and it looks like you can use the addConditions methods with an OR operator to accomplish your nested query.

There are 4 different overloaded methods with addConditions but the last two allow you to supply an operator (in your case OR) and one of those allows you to string together multiple conditions using a supplied operator.

So all you need to do is break apart your nested statements into separate conditions and then link them together with your addConditions([Collection of Conditions], OR) statement.



标签: java sql jooq