合并两个SQL查询或防止排除现有查询

时间:2016-01-26 19:48:43

标签: sql sql-server tsql

我有一个SQL查询:

SELECT 
    AnalyticsHub_Requests.Id AS reqId, AnalyticsHub_Requests.*,
    AnalyticsHub_StatusCodes.ShortDescription AS StatusText,
    Users.FullName + ' (' + COALESCE(WorkPhone,'Phone empty') + ')' AS Value, 
    Users.Id 
FROM 
    AnalyticsHub_StatusCodes 
INNER JOIN 
    (Users 
INNER JOIN 
    AnalyticsHub_Requests ON Users.[Id] = AnalyticsHub_Requests.[AssigneeId]) ON AnalyticsHub_StatusCodes.[Id] = AnalyticsHub_Requests.[StatusId]
WHERE  
    AnalyticsHub_Requests.StatusId = 4 
    OR AnalyticsHub_Requests.StatusId = 6;

当所有问题都有受让人时,这将返回3行数据。但是,如果问题没有受让人,则会从结果中省略。我尝试了几种不同的方法但无济于事。如何在结果中包含没有受让人的数据行?

1 个答案:

答案 0 :(得分:0)

使用RIGHT JOIN(如评论中所述)我能够阻止我的查询省略结果。

SELECT 
AnalyticsHub_Requests.Id AS reqId, AnalyticsHub_Requests.*,
AnalyticsHub_StatusCodes.ShortDescription AS StatusText,
Users.FullName + ' (' + COALESCE(WorkPhone,'Phone empty') + ')' AS Value, 
Users.Id 
FROM 
AnalyticsHub_StatusCodes 
INNER JOIN 
(Users 
RIGHT JOIN 
AnalyticsHub_Requests ON Users.[Id] = AnalyticsHub_Requests.[AssigneeId])     
ON AnalyticsHub_StatusCodes.[Id] = AnalyticsHub_Requests.[StatusId]
WHERE  
AnalyticsHub_Requests.StatusId = 4 
OR AnalyticsHub_Requests.StatusId = 6;