在SQL Server中将父级写入子组查询?

时间:2013-02-17 19:15:00

标签: sql-server stored-procedures

有没有更有效的方法来编写没有子查询的查询?

Question_Group

Question_Group_ID int, 
Question_Group_Name nvarchar, 
Question_Group_Indent int,  // 1=parent,2=child,3=grandchild
Question_Group_Order int, 
Question_Parent_ID int

我的查询:

SELECT 
   parent.Question_Group_Name, parent.Question_Group_Order, 
   L2Child.Question_Group_Name, L2Child.Question_Group_Order 
FROM
   (SELECT 
       Question_Group_ID, Question_Group_Name, Question_Group_Indent, 
       Question_Group_Order, Question_Parent_ID
    FROM
       Question_Groups 
    WHERE
       Question_Group_Indent = 1) parent
LEFT JOIN
   (SELECT
       Question_Group_ID, Question_Group_Name, Question_Group_Indent, 
       Question_Group_Order, Question_Parent_ID
    FROM 
       Question_Groups 
    WHERE 
       Question_Group_Indent = 2) L2Child ON parent.Question_Group_ID = L2Child.Question_Parent_ID
ORDER BY 
    parent.question_group_Order

结果:

Pre-Site            1   NULL                                    NULL
Agency Information  2   Contacts                            1
Agency Information  2   Contracting Services                    2
Agency Information  2   Start-Up Agency                         3
Agency Information  2   Hiring                                  4
Agency Information  2   Budgeted and Actual Sworn Force         5
Agency Information  2   CP Questions                            6
Hiring Grants   3       Per Hiring Grant Questions          1
Non-Hiring Grants   4   Per Non-Hiring Grant Questions          1

1 个答案:

答案 0 :(得分:0)

我不确定它是否更有效但你可以用CTE写它以使它更具可读性。

WITH parent AS (SELECT Question_Group_ID, Question_Group_Name, Question_Group_Indent, 
                    Question_Group_Order, Question_Parent_ID
                FROM Question_Groups 
                WHERE Question_Group_Indent=1),
     L2Child AS (SELECT Question_Group_ID, Question_Group_Name, Question_Group_Indent, 
                    Question_Group_Order, Question_Parent_ID
                FROM Question_Groups 
                WHERE Question_Group_Indent=2)
SELECT parent.Question_Group_Name, parent.Question_Group_Order, 
    L2Child.Question_Group_Name, L2Child.Question_Group_Order 
FROM parent
LEFT JOIN L2Child
    ON parent.Question_Group_ID = L2Child.Question_Parent_ID
ORDER BY parent.question_group_Order

另一种选择是以这种方式重写它

SELECT parent.Question_Group_Name, parent.Question_Group_Order, 
    L2Child.Question_Group_Name, L2Child.Question_Group_Order 
FROM Question_Groups AS parent
LEFT JOIN Question_Groups AS L2Child
    ON parent.Question_Group_ID = L2Child.Question_Parent_ID
    AND L2Child.Question_Group_Indent=2
WHERE parent.Question_Group_Indent=1
    ORDER BY parent.question_group_Order

阅读this,了解为什么我在WHERE子句中放入“左”表条件,在ON子句中放入“右”表条件。