自定义层次结构输出

时间:2014-05-24 03:32:15

标签: sql oracle

对于Oracle SQL 10g / 11g

我有三张表格如下 -

国家

ID NAME  
1 United States  
2 England  
3 India  

ID NAME  
11 Seattle  
21 Bristol  
31 Mumbai  

Country_City

country_ID city_id  
1 11  
2 21  
3 31  

是否可以获得可以区分国家和州的分层输出?

2 个答案:

答案 0 :(得分:0)

如果您尝试以下内容怎么办?在此处查看演示http://sqlfiddle.com/#!2/94f19/2

select c.NAME as Country,cc.NAME as City
from Country c
inner join country_City c1
on c.ID = c1.country_ID
inner join City cc
on cc.ID = c1.city_id

答案 1 :(得分:0)

如果我理解正确,您可以使用union all获得所需的输出。 id列用于将一个国家/地区内的所有内容保存在一起。 ordering列用于确保国家/地区名称是第一个:

select name
from ((select cc.id, c.name, 1 as ordering
       from country_city cc join
            country c
            on cc.countryid = c.id 
      ) union all
      (select cc.id, ci.name, 2 as ordering
       from country_city cc join
            city ci
            on cc.cityid = ci.id 
      )
     ) c
order by id, ordering;