1

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

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
4

1 回答 1

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

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

于 2013-02-17T20:34:33.550 回答