即使一个compairson不相等,使用多个JOINS的SELECT也需要返回

时间:2013-09-17 13:58:17

标签: sql sql-server

我一直致力于查询:

SELECT P.[Name]+' - '+P.[Description] AS Sprint, S.[Number] AS Story, T.[Name] AS Task
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task 
INNER JOIN Story S ON T.StoryId = S.PK_Story 
INNER JOIN Sprint P ON S.SprintId = P.PK_Sprint 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

Sprint列可能是也可能不是NULL:

enter image description here

如果存在关联的SprintId,则上述查询将仅返回请求的列。如果为NULL,则不返回整列。这是有道理的,当Story表上为NULL时,S.SprintId = P.PK_Sprint不是等效的。

如果它为NULL,我仍然希望它返回包含所有其他表列数据的行,但是使用单词KanBan而不是不返回任何内容。我如何实现这一目标?

3 个答案:

答案 0 :(得分:2)

S.Number更改为ISNULL(S.Number, 'KanBan')。如果在Sprint表中找不到匹配的sprintID,则会添加“看板”。

INNER JOIN Sprint P ON S.SprintId = P.PK_Sprint更改为LEFT JOIN Sprint P ON S.SprintId = P.PK_Sprint。这确保即使在不匹配的情况下,所有其他记录仍将显示。

然后完整查询变为:

SELECT P.[Name]+' - '+P.[Description] AS Sprint, ISNULL(S.Number, 'KanBan') AS Story,     T.[Name] AS Task
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task 
INNER JOIN Story S ON T.StoryId = S.PK_Story 
LEFT JOIN Sprint P ON S.SprintId = P.PK_Sprint 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

答案 1 :(得分:2)

SELECT ISNULL(P.[Name]+' - '+P.[Description],'KanBan') AS Sprint, S.[Number] AS Story, T.[Name] AS Task
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task 
INNER JOIN Story S ON T.StoryId = S.PK_Story 
LEFT OUTER JOIN Sprint P ON S.SprintId = P.PK_Sprint 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

答案 2 :(得分:1)

试试这个

  SELECT P.[Name]+' - '+P.[Description] AS Sprint, S.[Number] AS Story, T.[Name] AS Task
    FROM DailyTaskHours D
    INNER JOIN Task T ON D.TaskId = T.PK_Task 
    INNER JOIN Story S ON T.StoryId = S.PK_Story 
    LEFT OUTER JOIN Sprint P ON S.SprintId = P.PK_Sprint 
    GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

请查看Difference between inner and outer join