表1 Questions
ID | Name | Category
1 | xyz | 1
2 | abc | 1
3 | ghj | 2
4 | tyu | 3
表2 Data
ID | QuestionID | Category
1 | 2 | 1
2 | 3 | 2
我希望结果是Question
表中的所有问题。 WHERE Category = 1
ID | Question | DataID
1 | xyz | NO
2 | abc | YES (data id=1 ie questionid= 2)
3 | ghj | NO (data id=2 ie questionid= 3 but where category = 2 fail so 'NO')
4 | tyu | NO
所以如果数据存在,我需要显示YES。否则
答案 0 :(得分:2)
您可以尝试LEFT JOIN
以及CASE WHEN
声明。
以下是查询:
SELECT
Q.ID,
Q.Name AS 'Question',
CASE WHEN D.QuestionID IS NULL THEN 'NO' ELSE 'YES' END AS DataID
FROM Questions Q LEFT JOIN Data D
ON Q.ID = D.QuestionID
ORDER BY Q.ID;
修改强>
根据您的编辑要求
我希望结果是问题表中的所有问题。哪里 Category = 1
<强>查询:强>
SELECT
Q.ID,
Q.Name AS 'Question',
CASE WHEN D.QuestionID IS NULL OR D.category <> 1 THEN 'NO' ELSE 'YES' END AS DataID
FROM Questions Q LEFT JOIN Data D
ON Q.ID = D.QuestionID
ORDER BY Q.ID;