Lokomotywa
Lokomotywa

Reputation: 2844

How do I modify a SQL JOIN with an OR operator such that the second condition only gets evaluated when the first fails

In case table be as the row (x=1,y=1) and f has the rows ((x=1, y=1), (x=1, y=2))

I want to achieve one result row only, since the first condition is met, the second ought to be ommited.

Select * from be join f        
ON ( (be.x = f.x AND f.y = b.y) OR (be.x = f.x))

Upvotes: 0

Views: 225

Answers (2)

Serg
Serg

Reputation: 22811

Looks like you want NOT EXISTS.

Select * 
from be 
join f on (be.x = f.x and f.y = be.y) 
       or (be.x = f.x and not exists (
            select 1 
            from f f2
            where be.x = f2.x and f2.y = be.y))

Upvotes: 1

Lokomotywa
Lokomotywa

Reputation: 2844

Found a solution myself:

select distinct on (be.x)
f.y = b.y as condition_met
* from be join f 
ON ( (be.x = f.x AND f.y = b.y) OR (be.x = f.x))
order by be.x, condition_met desc

Upvotes: 0

Related Questions