不正确的SQL语句

时间:2016-03-31 02:45:22

标签: php mysql sql

表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。否则

1 个答案:

答案 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;

MySQL JOINS

Demo Here

修改

根据您的编辑要求

  

我希望结果是问题表中的所有问题。哪里   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;

Updated Demo