Skip to content
Advertisement

sql join gives cumulative results

I want to join county and county_type tables and get only those county that doesnt have a type =30. From below example id = 1 and 3 should only be the expected output county

id  name    zipcode
1   LC      12345
2   WC      98765   
3   AC      09876
4   VC      90876

county_type
id  type
1   10
1   20
2   10
2   20
2   30
3   10
3   20
4   10
4   20
4   30

output:

id  name    zipcode
1   LC      12345
3   AC      09876

Tried this:

select *.c from county c, county_type ct
where c.id = ct.id
and ct.id != 30
order by c.id asc;

what i am getting is cumulative:

id  name    zipcode
1   LC      12345
1   LC      12345
2   WC      98765
2   WC      98765........///

Advertisement

Answer

You want not exists:

select c.*
from county c
where not exists (select 1
                  from county_type ct
                  where ct.id = c.id and ct.type = 30
                 );
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement