我有一个SQL Server查询:
SELECT top 1 vConsentInfo FROM
(
SELECT cons.vConsentInfo,cons.dTimeStamp ,logs.iPartnerProfileID
FROM H_OutMessageLog logs INNER JOIN H_OutMessageConsent cons on cons.iOutMessageQID = logs.iOutQueueID
WHERE logs.iPatID = 65686 and logs.iPracID = 4
UNION
SELECT cons.vConsentInfo,cons.dTimeStamp,Q.iPartnerProfileID
FROM H_OutMessageQueue Q INNER JOIN H_OutMessageConsent cons on cons.iOutMessageQID = Q.iOutQueueID
WHERE Q.iPatID = 65686 and Q.iPracID = 4
) A
WHERE A.iPartnerProfileID = Prof.IPartnerProfileID
Order BY dTimeStamp DESC
该表的作用如下:记录在开始时插入H_OutMessageQueue
;然后将其插入H_OutMessageConsent
...
现在有一个单独的工作进程处理来自H_OutMessageQueue
的记录并将其记录到H_OutMessageLog
....
我可以摆脱这个UNION
的事吗?请注意,这是较大CTE
查询的子查询。
答案 0 :(得分:5)
是的,但可能更好。您必须将其用于更大的查询
SELECT TOP 1
cons.vConsentInfo,
ISNULL(logs.iPartnerProfileID , Q.iPartnerProfileID) AS iPartnerProfileID
FROM
H_OutMessageConsent cons
LEFT JOIN
H_OutMessageLog logs ON cons.iOutMessageQID = logs.iOutQueueID AND
logs.iPatID = 65686 and logs.iPracID = 4
LEFT JOIN
H_OutMessageQueue Q ON cons.iOutMessageQID = Q.iOutQueueID AND
Q.iPatID = 65686 and Q.iPracID = 4
WHERE
ISNULL(logs.iPartnerProfileID , Q.iPartnerProfileID) IS NOT NULL
ORDER BY
cons.dTimeStamp DESC
答案 1 :(得分:1)
除了gbn回复。这将消除查询中的额外负担:)。
SELECT top 1 vConsentInfo FROM
(
SELECT cons.vConsentInfo,cons.dTimeStamp ,logs.iPartnerProfileID
From
(
Select iPartnerProfileID FROM H_OutMessageLog logs
WHERE logs.iPatID = 65686 and logs.iPracID = 4
)logs
Left JOIN H_OutMessageConsent cons on cons.iOutMessageQID = logs.iOutQueueID
UNION
SELECT cons.vConsentInfo,cons.dTimeStamp,Q.iPartnerProfileID
From
(
Select iPartnerProfileID FROM H_OutMessageQueue Q
WHERE Q.iPatID = 65686 and Q.iPracID = 4
)Q
Left JOIN H_OutMessageConsent cons on cons.iOutMessageQID = Q.iOutQueueID
) A
WHERE A.iPartnerProfileID = Prof.IPartnerProfileID
Order BY dTimeStamp DESC