【问题标题】:Sql query to get the GrandFather name by doing a self join通过执行自联接获取祖父名称的 Sql 查询
【发布时间】:2010-04-28 05:59:05
【问题描述】:

任何人都可以给我查询以获取孩子的名字和他的祖父的名字例如 - 如果我有一个表关系在我有 childid 和 Fatherid 列那么我将如何得到祖父,

我可以通过使用连接轻松获得父亲的名字,但对于祖父,我需要进行 2 次连接,所以任何人都可以帮我解决这个问题

D.马赫什

【问题讨论】:

    标签: sql-server self-join


    【解决方案1】:

    只需添加一个类似于您已有的附加连接。

     select grandparent.name, child.name
     from Relationships child
     inner join Relationships parent
      on child.parentid = parent.id
     inner join Relationships grandparent
      on parent.parentid = grandparent.id
    

    【讨论】:

    • 您好,Oded,感谢您的及时回复,我试过了,这正是我想要的。再次感谢 D.Mahesh
    【解决方案2】:

    我认为它可以通过如下的单一连接来实现-

    select t2.fatherid as grandfather 
    from table1 as t1 
    inner join table1 as t2 on t1.fatherid=t2.childid 
    where t1.childid='grandson_id';
    

    【讨论】:

    • 您好萨达特,感谢您的回复,我尝试了您的查询,但它只给了我父亲的名字而不是祖父的名字 D.Mahesh
    • @Sadat:如果您发布代码,例如 T-SQL 代码,使用编辑器工具栏上的代码按钮 (101 010) 将这些行格式化为代码 - 它们获得良好的格式并因此获得语法突出显示,并且更好阅读!
    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多