分层数据的检索
Retrieval of hierarchial data
我有一个 select 地区的区域代码,基于一次查询中的类型。
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
预期:
India TamilNadu TamilNadu
India Karnataka Karnataka
India Chennai TamilNadu
India Bangalore Karnataka
实际
India TamilNadu TamilNadu
India Karnataka Karnataka
这看起来比较复杂。您可以使用 union all
做您想做的事——一份用于各州,一份用于城市。
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;
我有一个 select 地区的区域代码,基于一次查询中的类型。
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
预期:
India TamilNadu TamilNadu
India Karnataka Karnataka
India Chennai TamilNadu
India Bangalore Karnataka
实际
India TamilNadu TamilNadu
India Karnataka Karnataka
这看起来比较复杂。您可以使用 union all
做您想做的事——一份用于各州,一份用于城市。
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;