如何在sql中获取自引用列值

时间:2016-08-11 14:27:49

标签: sql-server

我有两个列

的表
CREATE TABLE Dept(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Next_ID] [int] NULL,
    [Name] [varchar](50) NOT NULL,
    [Bundle_ID] [int] NULL
)

并且

CREATE TABLE Bundle(
    [Bundle_ID] [int] NOT NULL,
    [Bundle_Name] [varchar](40) NOT NULL
)

我想获取nextID名称,所以我尝试了

SELECT dept.ID, dept.Next_ID, currentbundle.Bundle_Name CurrentBundleName
FROM Dept dept
      join Bundle currentbundle on currentbundle.Bundle_ID = dept.Bundle_ID
      join dept dept1 on dept1.Next_ID=dept.ID

有了这个,我只得到currentBundleName。如何获取nextbundlename?

我希望有这样的输出

ID       NextID      CurrentBundleName    NextBundleName
********************************************************
1        3           template             excel
3        4           excel                word
4        NULL        word                 NULL

2 个答案:

答案 0 :(得分:1)

请试试这个:

SELECT d.id, 
d.next_id, 
b.Bundle_Name current_bundle_name, 
b1.Bundle_Name AS next_bundle_name
FROM dept d
INNER JOIN bundle b ON b.Bundle_ID = d.Bundle_ID
LEFT JOIN bundle b1 ON b1.Bundle_ID = d.Next_ID

答案 1 :(得分:1)

CREATE TABLE #Dept(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Next_ID] [int] NULL,
    [Name] [varchar](50) NOT NULL,
    [Bundle_ID] [int] NULL
)


CREATE TABLE #Bundle(
    [Bundle_ID] [int] NOT NULL,
    [Bundle_Name] [varchar](40) NOT NULL
)

INSERT INTO #Bundle
        ( Bundle_ID, Bundle_Name )
VALUES  
( 1, 'One'  ),
( 2, 'Two'  ),
( 3, 'Three'  ),
( 4, 'Four'  )

INSERT INTO #Dept
        ( Next_ID, Name, Bundle_ID )
VALUES  
( NULL,  'First',  1),
( 1,  'Second',  2),
( 2,  'Third',  3),
( 3,  'Fouth',  4)


select 
    d.ID,
    d.Name          AS DeptName,
    d2.ID           AS NextDeptId,
    d2.Name         AS NextDeptName,
    b.Bundle_Name   AS BundleName,
    b2.Bundle_Name  AS NextBundleName
FROM #Dept d
JOIN #Bundle b  ON b.Bundle_ID = d.Bundle_ID
LEFT JOIN #Dept d2  ON d2.id=d.Next_ID
LEFT JOIN #Bundle b2 ON b2.Bundle_ID = d2.Bundle_ID

DROP TABLE #Bundle
DROP TABLE #Dept

更正结果:

ID  DeptName    NextDeptId  NextDeptName    BundleName  NextBundleName
1   First       NULL        NULL            One         NULL
2   Second      1           First           Two         One
3   Third       2           Second          Three       Two
4   Fouth       3           Third           Four        Three