我有一个评估结果数据库,其中包含识别学生,年级,年份和学期的字段。下面的查询找到了在某个起点和终点对特定主题进行评估的学生:
SELECT
a1.PupilId
FROM assessment as a1
JOIN assessment as a2
USING (PupilId)
WHERE a1.GradeID in('1A','1B','1C')
AND a2.GradeID in('5A','5B','5C')
AND a1.NCYear = '1'
AND a1.Term = '6'
AND a2.NCYear = '2'
AND a2.Term = '6'
AND a1.Subject = '31'
AND a2.Subject = '31'
AND a1.Type = 'assessment'
AND a2.Type = 'assessment'
这种方法很好,但现在我想找到具有起始等级的学生(即NCYear ='1'和Term ='6'),但没有最终成绩的条目。我玩过NOT EXISTS,但无法让它工作。
澄清一下,这是评估表:
id | Subject | PupilId | NCYear | Term | GradeID | Type
--------------------------------------------------------
1 | 31 | 1 | 1 | 6 | 1A | assessment
2 | 31 | 1 | 2 | 6 | 5A | assessment
3 | 31 | 2 | 1 | 6 | 1A | assessment
上面的SQL查询应该返回PupilID 1.我需要返回PupilID 2的查询,开始评估在那里,但没有结束。
有什么建议吗?
答案 0 :(得分:0)
使用if
尝试此查询SELECT
a1.PupilId
FROM assessment as a1
JOIN assessment as a2
USING (PupilId)
WHERE a1.GradeID in('1A','1B','1C')
AND a2.GradeID in('5A','5B','5C')
AND a1.NCYear = '1'
AND a1.Term = '6'
AND a2.NCYear = '2'
AND a2.Term = '6'
AND a1.Subject = '31'
AND a2.Subject = '31'
AND a1.Type = 'assessment'
AND a2.Type = 'assessment'
AND IF(a1.NCYear = 1, IF(a1.Term = 6,a2.GradeID IS NULL,1),1)
答案 1 :(得分:0)
您需要使用OUTER JOIN:
SELECT
a1.PupilId
FROM assessment as a1
OUTER JOIN assessment as a2
ON a2.PupilId = a2.PupilId AND a2.NCYear = '2' AND a2.GradeID in('5A','5B','5C') AND a2.Term = '6' AND a2.Subject = '31' AND a2.Type = 'assessment'
WHERE a1.GradeID in('1A','1B','1C')
AND a1.NCYear = '1'
AND a1.Term = '6'
AND a1.Subject = '31'
AND a1.Type = 'assessment'
AND a2.PupilId IS NULL