[英]SQL LEFT OUTER JOIN Query, need to add a WHERE CLAUSE
I have this query here: 我在这里有此查询:
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
This returns all items in TPM_Questions_Default and if a QuestionID does not exist in the customerQuestions the bools are false automatically 这将返回TPM_Questions_Default中的所有项目,如果customerQuestions中不存在QuestionID,则布尔值会自动为false
Now I need to reuse this query else where but I need to add in another WHERE CLAUSE ( AND Q.Question_ID = 2
) which needs to return one row. 现在,我需要在其他地方重用此查询,但是我需要添加另一个WHERE子句(
AND Q.Question_ID = 2
),该子句需要返回一行。
When I add it to the end of the query it still returns all items in TPM_Questions_Default, I just need it to return one. 当我将其添加到查询末尾时,它仍然返回TPM_Questions_Default中的所有项目,我只需要它返回一个即可。 How can I adjust this query to do what I want?
如何调整此查询以执行我想要的操作?
I suspect you are adding it to your JOIN clause: 我怀疑您是将其添加到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
When you should be adding it as a WHERE
clause: 当您将其添加为
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.