[英]Oracle SQL query to return 1 or 0 based on if value exists
I have 2 table Question and Answer tables. 我有2个表Question and Answer表。 Question table has 问题表有
ID Question_Text
1 Question1
2 Question2
3 Question3
Answer table 答案表
Question_ID Answer_text Answered_by
1 Ans1 User1
1 Ans2 User2
1 Ans3 User3
2 Ans4 User1
I need to find out which all questions were answered already? 我需要找出所有已回答的问题? Desired outcome 期望的结果
ID Question_Text Answered
1 Question1 true/1
2 Question2 true/1
3 Question3 false/0
I have written the below query to find whether the question is answered by using EXISTS. 我写了下面的查询,以查找是否通过使用EXISTS回答了问题。 I need answered value true/false and also want to fine tune this query so that it checks for first occurrence in answer table and get the value as true/false, instead of running through the thousands of value in answer table. 我需要答案值为true / false,并且还希望对该查询进行微调,以便它检查答案表中的第一个匹配项并获取值为true / false,而不是遍历答案表中的数千个值。
SELECT *
FROM QUESTIONS A
WHERE EXISTS (SELECT *
FROM ANSWERS B
WHERE A.QUESTION_ID = B.QUESTION_ID);
A simple LEFT JOIN
will do: 一个简单的LEFT JOIN
可以做到:
SELECT Q.*,
CASE WHEN A.Question_ID IS NULL THEN 0 ELSE 1 END Answered
FROM Question Q
LEFT JOIN ( SELECT DISTINCT Question_ID
FROM Answer) A
ON Q.ID = A.Question_ID;
Try: SELECT Q.*, CASE WHEN EXISTS ( SELECT * FROM ANSWERS A WHERE A."Question_ID" = Q.ID ) THEN 'true/1' ELSE 'false/0' END Answered FROM QUESTIONS Q ORDER BY ID
尝试: SELECT Q.*, CASE WHEN EXISTS ( SELECT * FROM ANSWERS A WHERE A."Question_ID" = Q.ID ) THEN 'true/1' ELSE 'false/0' END Answered FROM QUESTIONS Q ORDER BY ID
This has the advantage of not having to DISTINCT
ANSWERS first. 这样做的好处是不必首先DISTINCT
答案。 If ANSWERS is big and has an index on Question_ID it may be faster, especially for selected questions. 如果ANSWERS很大并且在Question_ID上有索引,则可能会更快,尤其是对于选定的问题。 It's still not a proper semi-join solution. 它仍然不是适当的半联接解决方案。 The query optimiser could surprise with both this and the @Lamak solution using real data. 查询优化器可能对此以及使用实际数据的@Lamak解决方案都感到惊讶。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.