sql - How to make a condition on join table -


if have 2 tables :

location :

loc_id loc_name   1     xx   2     yy   3     zz 

group :

grp_id loc_id   3      2 

now if there's group want related locations if not want whole location table .

i query :

select distinct a.loc_id , a.loc_name  location  left join group b on a.loc_id = b.loc_id   (b.grp_id = 3 or (b.group_id null)) 

but locations time cuz use oring

try this:

select loc_id, loc_name location l exists (select *                group g               l.loc_id = g.loc_id ,                     g.grp_id = 3)  union  select loc_id, loc_name location  not exists (select *                   location l                   join group g on l.loc_id = g.loc_id                   g.grp_id = 3) 

if there matching location records group specified, these records returned first query of union all operation. second query return empty set in case.

if there no matching records, first query return empty set, whereas second query return all records of table location.


Comments