平面视图的亲子关系

发布于 2024-12-05 20:44:30 字数 404 浏览 0 评论 0原文

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

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

提前致谢

Is there an easy way to migrate a table with a parent child relation to a column one ?

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

OUTPUT

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

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若水微香 2024-12-12 20:44:30

如果您根据注释拥有 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

Provided you have a hierarchie of 3 items as per your comments and there's no need to retain rows that have no City or Place, joining the table twice with itself would suffice.

SQL Statement

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) Test script

;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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文