-2

I have a region code to select area based on type in one query.

Table place:

regionname regiontype placeid parentplaceid
-------------------------------------------
Chennai    city        4        2
Bangalore  city        3        1
TamilNadu  state       2        2
Karnataka  state       1        1

Table Country:

countryname State

India       TamilNadu
India       Karnataka
select  c.countryname, p.regionname, c.State
from place p,
     country c
where p.regionname = c.State

Expected:

India       TamilNadu   TamilNadu
India       Karnataka   Karnataka
India       Chennai     TamilNadu
India       Bangalore   Karnataka

Actual

India       TamilNadu   TamilNadu
India       Karnataka   Karnataka

1 Answers1

0

This seems rather complicated. You can do what you want using union all -- one part for the states and one for the cities.

select c.countryname, p.regionname, p.state
from place p join
     country c
     on p.regiontype = 'state' and
        p.regionname = c.state
union all
select c.countryname, p.regionname, ps.state
from place p join
     place ps
     on p.parentplaceid = ps.placeid and
        p.regiontype = 'city' and
        ps.regiontype = 'state' join
     country c
     on ps.regionname = c.state;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786