【问题标题】:What is Self Join and how to write self join for more than 3 tables?什么是自联接以及如何为 3 个以上的表编写自联接?
【发布时间】:2016-07-30 16:21:37
【问题描述】:

我知道内连接、左连接、右连接、外连接。 什么是自加入? 任何人都可以解释一下什么是自加入,它的用途以及在哪里使用。

然后我也想知道如何使用自连接来连接三个以上的表。

例如客户表

1)CustomerID uniqueidentifier 主键不为空, 2) 客户名 Varchar(100), 3)CustomerTypeID uniqueidentifier null,

客户类型

1)CustomerTypeID uniqueidentifier 主键不为空 2)CustomerType varchar null

客户地址表

1)CustomerAddressID uniqueidentifier 主键不为空 2)CustomerID uniqueidentifier null, 3)AddressID uniqueidentifier null,

地址

1)AddressID uniqueidentifier 主键不为空, 2) 街道 varchar(100) 空值, 3) 位置 varchar(100) 空值, 4)放置varchar(100), null, 5)AreaID 唯一标识符为空, 6)PinCode Varchar(100)

区域

1)AreaID uniqueidentifier 主键不为空, 2)面积 Varchar(100)

这里我提到了一些表格。现在我想显示 CustomerName、CustomerType、Street、Place、Location、Area、PinCode。现在我如何为这些表添加自连接。请任何人解释这个概念。

【问题讨论】:

    标签: sql-server-2008 join


    【解决方案1】:

    自连接是将一个表连接到自身。这是在如下场景中完成的-

    TableProductCategory


    ID     CategoryName ParentCategoryID
    
    1      Clothes       NULL
    2      Jeans         1
    3      Shorts        1
    

    因此,在这种情况下,如果您需要列出类别名称及其父类别名称,您将使用如下所示的自联接

    Select A.CategoryName, B.CategoryName as ParentCategoryName
    from
    TableProductCategory A LEFT JOIN TableProductCategory B
    on A.ParentCategoryID=B.ID
    

    根据您的要求

    CustomerName , CustomerType, Street,Place,Location, Area, PinCode

    您需要使用简单的LEFT JOIN 如下查询

    Select 
    C.CustomerName, 
    T.CustomerType, 
    A.Street, 
    A.Place, 
    A.Location,
    AA.Area, 
    A.Pincode
    From 
      Customer C 
       LEFT JOIN CustomerType T on C.CustomerTypeID=T.CustomerTypeID
       LEFT JOIN CustomerAddress CA on C.CustomerID =CA.CustomerID 
       LEFT JOIN Address A on A.AddressID=CA.AddressID
       LEFT JOIN Area AA on AA.AreaID=A.AreaID
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2012-03-20
      相关资源
      最近更新 更多