如果记录存在与否,则sqlite显示1和0不起作用

时间:2015-01-20 14:07:26

标签: sql sqlite case

我想继续前一步question 因此,假设我们有一些学生在特定时间段参加某些课程,我们会得到这些表格

student

attends

course

其中粗体字段是主键

在Attends表中,atndsId PK, (stRegNum,courseCode,periodId)FK

对于 ID = 00001 的学生,我想要显示所有参加过1分的课程,而不是那些不参加分数的课程。喜欢这个

enter image description here

我创建了一个查询以查看它是如何工作的

select (
  case when exists(
    select 1
    from course 
    where attends.stRegNum = '00001' 
    group by course.courseCode
  )
  then 1
  else 0
  end
) as hh, *
from course left join attends on course.courseCode = attends.courseCode

我得到了这个

whatIget

这显然是错误的。我知道左派加入混乱,但我尝试的一切,我都无法得到预期的结果。

有人可以告诉我,我做错了什么,以及如何解决?提前谢谢。

PS: 我不确定标题。如果你有更好的主意,请提出建议!

1 个答案:

答案 0 :(得分:1)

对于学生'00001',您可以通过首先选择所有课程然后加入出席表来查看他们参加过哪些课程,标记为00001所参加的所有课程:

select distinct
        course.courseCode
        ,case when attends.attendsId is not null then 1 else 0 end as attendedCourse

from course 
        left join attends
        on course.courseCode = attends.courseCode
        and attends.stRegNum = '00001'