如何通过连接两个表来编写查询?

时间:2016-01-08 16:14:47

标签: sql sql-server join

我有两张桌子:

表1:

 ID NAME
 1      ID1
 2      ID2
 3      ID3
 4      ID4
 5      ID5
 6      ID6
 7      ID7

表2:

Parent_ID   Child_ID
    1         2
    2         5
    2         3
    3         6

如果我在where where condition中指定Parent_Id = 1,如何编写查询以获得低于输出?

P_ID    NAME    Is_Group    Selected
 1      ID1       Yes         No
 2      ID2       Yes         Yes
 3      ID3       Yes         Yes 
 4      ID4       No          No
 5      ID5       No          Yes 
 6      ID6       No          Yes
 7      ID7       No          No

因此,输出主要包含来自表1的记录,但它还需要有两个额外的列。

Is_Group列中的值应为"是"如果表1中的ID存在于表2的Parent_ID列中,则Selected列中的值应为" yes"如果表1中的ID存在于表2中的Child_ID列中,并且Parent_ID = 1(如交叉引用)。

另外,我需要检查Child_ID是否有任何交叉引用。例如,在表2中,Parent_ID为2,Parent_Id为1,2还有5和3为child_Id,因此我需要将Selected列值设置为"是"对于Id 3和5等等。

预先感谢您的回复。对不起我的英语不好。

2 个答案:

答案 0 :(得分:0)

这应该可以为您提供所需的输出。

它使用递归cte来获取层次结构。

然后外部连接到cte两次以确定ID是否为Group,或者通过检查空值来选择

WITH    cte AS
(   
    SELECT  Parent_ID,
            Child_ID
    FROM    Table2
    WHERE   Parent_ID = 1
    UNION ALL
    SELECT  t2.Parent_ID,
            t2.Child_ID
    FROM    Table2 t2
            INNER JOIN cte ON t2.Parent_ID = cte.Child_ID
)
SELECT DISTINCT
        t1.*,
        (CASE WHEN grp.Parent_ID IS NULL THEN 'No'
                ELSE 'Yes'
            END) AS Is_Group,
        (CASE WHEN sel.Parent_ID IS NULL THEN 'No'
                ELSE 'Yes'
            END) AS Selected
FROM    Table1 t1
        LEFT JOIN cte grp ON t1.ID = grp.Parent_ID
        LEFT JOIN cte sel ON t1.ID = sel.Child_ID

您从Table1中选择所有内容,无论其是否在所选层次结构中,都会为任何ID为Parent_ID的Is_Group提供No,但实际上并不是在层次结构中。要始终确定ID是否为Group,只需将表2作为grp而不是cte ...添加到表。

;WITH    cte AS
(   
    SELECT  Parent_ID,
            Child_ID
    FROM    Table2
    WHERE   Parent_ID = 1
    UNION ALL
    SELECT  t2.Parent_ID,
            t2.Child_ID
    FROM    Table2 t2
            INNER JOIN cte ON t2.Parent_ID = cte.Child_ID
)
SELECT DISTINCT
        t1.*,
        (CASE WHEN grp.Parent_ID IS NULL THEN 'No'
                ELSE 'Yes'
            END) AS Is_Group,
        (CASE WHEN sel.Parent_ID IS NULL THEN 'No'
                ELSE 'Yes'
            END) AS Selected
FROM    Table1 t1
        LEFT JOIN Table2 grp ON t1.ID = grp.Parent_ID
        LEFT JOIN cte sel ON t1.ID = sel.Child_ID

答案 1 :(得分:0)

试试这个,

select distinct id, t.NAME, 
    case when t1.Parent_ID is not null then 'Yes' else 'No' end Is_Group
     ,case when b.Child_ID is null then 'No' else 'Yes' end Selected 
     from Table1 t   left join    Table2 t1 on t.ID =t1.Parent_ID
      outer apply (select Child_ID from Table2 a where a.Child_ID=t.ID ) b