我在这里有这个问题:
SELECT
Q.Question_ID,
Q.Question,
Q.Department,
CASE WHEN C.selected = 'true' THEN CAST('true' AS BIT) ELSE CAST('false' AS BIT) END AS Selected
FROM TPM_Questions_Default AS Q
LEFT OUTER JOIN customerQuestions AS C
ON Q.Question_ID = C.QuestionID
AND C.CustomerID = 123456
这将返回TPM_Questions_Default中的所有项目,如果customerQuestions中不存在QuestionID,则bools会自动为假
现在我需要在其他地方重用此查询,但我需要添加另一个需要返回一行的WHERE CLAUSE(AND Q.Question_ID = 2
)。
当我将它添加到查询的末尾时,它仍然返回TPM_Questions_Default中的所有项目,我只需要它返回一个。如何调整此查询以执行我想要的操作?
答案 0 :(得分:2)
我怀疑你是将它添加到你的JOIN子句中:
SELECT
Q.Question_ID,
Q.Question,
Q.Department,
CASE WHEN C.selected = 'true' THEN CAST('true' AS BIT) ELSE CAST('false' AS BIT) END AS Selected
FROM TPM_Questions_Default AS Q
LEFT OUTER JOIN customerQuestions AS C
ON Q.Question_ID = C.QuestionID
AND C.CustomerID = 123456
AND Q.Question_ID = 2
何时应将其添加为WHERE
子句:
SELECT
Q.Question_ID,
Q.Question,
Q.Department,
CASE WHEN C.selected = 'true' THEN CAST('true' AS BIT) ELSE CAST('false' AS BIT) END AS Selected
FROM TPM_Questions_Default AS Q
LEFT OUTER JOIN customerQuestions AS C
ON Q.Question_ID = C.QuestionID
AND C.CustomerID = 123456
WHERE Q.Question_ID = 2