在SQL Server中将两个小选择合并为一个

时间:2014-06-20 07:56:06

标签: sql sql-server select stored-procedures

我使用以下嵌套选择作为更大查询的一部分。

有没有办法可以将它们合二为一,这样我就不必再运行两个查询?

// ...
R.requester,
(
    SELECT      A.Email AS requesterEmail
    FROM        LogTable A
    WHERE       A.NTID = R.requester
    FOR XML PATH(''), ELEMENTS, TYPE
),
R.approver,
(
    SELECT      B.Email AS approverEmail
    FROM        LogTable B
    WHERE       B.NTID = R.approver
    FOR XML PATH(''), ELEMENTS, TYPE
),
// ...

2 个答案:

答案 0 :(得分:2)

SELECT A.Email AS requesterEmail,B.Email AS approverEmail
    FROM  LogTable B
JOIN LogTable A
    ON B.NTID = R.approver AND A.NTID = R.requester
    FOR XML PATH(''), ELEMENTS, TYPE

答案 1 :(得分:1)

如果查询返回相同的数据,您可以使用UNION ALL

SELECT      A.Email AS requesterEmail
FROM        LogTable A
WHERE       A.NTID = R.requester
FOR XML PATH(''), ELEMENTS, TYPE

union all

(
   SELECT      B.Email AS approverEmail
   FROM        LogTable B
   WHERE       B.NTID = R.approver
   FOR XML PATH(''), ELEMENTS, TYPE
)