亲子关系到平面视图

时间:2011-09-21 12:27:18

标签: sql parent-child

是否有一种简单的方法可以将具有父子关系的表迁移到第一列?

INPUT_TABLE

PARENT_ID,ID,NAME
null,1, USA
1   ,2, Las Vegas
2   ,3, City in las Vegas
2   ,4, Another City in las Vegas
.. a lot more

输出

ID, COUNTRY, CITY, PLACE
1,  USA, null,null
2,  USA, Las Vegas,null
3,  USA, Las Vegas,City in las Vegas
4,  USA, Las Vegas,Another City in las Vegas

提前致谢

1 个答案:

答案 0 :(得分:1)

根据您的评论,如果你有3个项目的层级,并且不需要保留没有CityPlace的行,那么将表连接两次就足够了。

SQL语句

SELECT  ID = Country.ID
        , Country = Country.NAME
        , City = City.NAME
        , Place = Place.Name
FROM    q Country
        INNER JOIN q City ON City.PARENT_ID = Country.ID
        INNER JOIN q Place ON Place.PARENT_ID = City.ID

(SQL Server)测试脚本

;WITH q (PARENT_ID, ID, NAME) AS (
  SELECT null, 1, 'USA'
  UNION ALL SELECT 1, 2, 'Las Vegas'
  UNION ALL SELECT 2, 3, 'City in las Vegas'
  UNION ALL SELECT 2, 4, 'Another City in las Vegas'
)
SELECT  ID = Country.ID
        , Country = Country.NAME
        , City = City.NAME
        , Place = Place.Name
FROM    q Country
        INNER JOIN q City ON City.PARENT_ID = Country.ID
        INNER JOIN q Place ON Place.PARENT_ID = City.ID