检索所有级别的层次结构 - 在sql上连接两个表?

时间:2016-08-02 11:53:23

标签: sql sql-server

表1

ID  title
1   a1          
2   b           
3   c1  

表2

tId title2  PId     
1   a      null     
2   b       1       
3   c       2

输出如:

    a1
    a1 > b
    b >  c1

查询

SELECT
  T2.PId,
  CASE
    WHEN T3.Title != '' THEN T3.Title + '>' + T2.title2
  END AS title
FROM (SELECT
  T2.PId,
  T2.title
FROM (SELECT
  T1.PgeId
FROM table1T1) P1
LEFT JOIN table2 T2
  ON P1.PgeId = T2.MId) T2
LEFT JOIN table2 T3
  ON T2.PId = T3.id

2 个答案:

答案 0 :(得分:0)

起初它对我来说似乎很混乱,但我发现关系是由table2定义的。这是解决方案:

WITH Table1 AS
(
    SELECT * FROM (VALUES
    (1, 'a1'),
    (2,'b'),
    (3,'c1')) T(ID, Title)
), Table2 AS
(
    SELECT * FROM (VALUES
    (1, 'a',NULL),
    (2,'b',1),
    (3,'c',2)) T(TId, Title, PId)
)
SELECT CASE WHEN T1_P.Title IS NOT NULL AND T1_T.Title IS NOT NULL THEN T1_P.Title + ' > ' + T1_T.Title
       WHEN T1_T.Title IS NOT NULL THEN T1_T.Title
       ELSE T1_P.Title END
FROM Table2 T2
LEFT JOIN Table1 T1_P ON T1_P.ID=T2.PId
LEFT JOIN Table1 T1_T ON T1_T.ID=T2.TId

答案 1 :(得分:0)

代码是:

CREATE TABLE #Table1 ( 
 ID         INT
,Title      NVARCHAR(20)
)
CREATE TABLE #Table2 ( 
     ID         INT
    ,Title      NVARCHAR(20)
    ,pID            INT
    )
INSERT INTO #Table1 (ID,Title) VALUES (1,'A1'),(2,'B'),(3,'C1')
INSERT INTO #Table2 (ID,Title,pID) VALUES (1,'A',NULL),(2,'B',1),(3,'C',2)

SELECT 
    CASE 
        WHEN T2.Title > T1.Title THEN T1.Title 
        WHEN T2.Title IS NULL THEN NULL
        ELSE T2.Title
    END AS Col1
    ,'>' AS H
    ,CASE 
        WHEN T2.Title < T1.Title THEN T1.Title 
        WHEN T1.Title IS NULL THEN NULL
        ELSE T2.Title
    END AS Col2
FROM #Table1 T1
RIGHT JOIN #Table2 T2 ON T1.ID = T2.pID

DROP TABLE #Table1
DROP TABLE #Table2

存在是:

enter image description here