Use if exists in postgresql [closed]
-
10-12-2020 - |
Вопрос
I know about the exists feature, but that does not help me with the given situation. What I want is:
Check if some row exists, and if exists then check for an another row if row exists.
Here's the sqlFiddle.
Description:
A location table:
| ID | NAME | ADDRESS |
|----|--------|---------|
| 1 | India1 | (null) |
| 2 | India2 | (null) |
| 3 | India3 | (null) |
| 4 | India4 | (null) |
| 5 | India5 | (null) |
Then a location_flag table:
| ID | LOCATION_ID | FLAG_ID | VALUE | PARENT_ID | DELETED |
|----|-------------|---------|-------|-----------|---------|
| 1 | 1 | 1 | YES | (null) | (null) |
| 2 | 1 | 2 | YES | (null) | (null) |
| 3 | 2 | 1 | YES | (null) | (null) |
| 4 | 2 | 2 | NO | (null) | (null) |
What I want is to get all locations except location with id=2.
In procedure, it'd be like:
if(locationWithFlag1='YES'){
if(locationWithFlag2='YES'){
//make this row to be appear in result
}
}
else{
//make this row appear in result
}
Is it possible without bringing in plpgsql?
Решение
select l.*
from location as l --- find all locations
where not exists --- where there isn't
( select *
from location_flag as lf --- a flag
where lf.location_id = l.id
and lf.flag_id = 1 --- with 1
and lf.value = 'YES' --- and YES
and not exists --- without
( select *
from location_flag as lf2 --- another flag
where lf2.location_id = l.id
and lf2.flag_id = 2 --- with 2
and lf2.value = 'YES' --- and YES
)
) ;
or:
select l.*
from location as l
where not exists
( select *
from location_flag as lf
where lf.location_id = l.id
and lf.flag_id = 1
and lf.value = 'YES'
)
or exists
( select *
from location_flag as lf2
where lf2.location_id = l.id
and lf2.flag_id = 2
and lf2.value = 'YES'
) ;
Не связан с dba.stackexchange