-1

我正在运行这个查询:

    select distinct(course.course) as course, count(students.studentid) as adm1,
    count(cclogs.newstudentid) from course
    left join students on (course.c_id=students.course and students.doa='2013-07-06')
    left join cclogs on (cclogs.newcid=course.c_id and doc='2013-07-06' and
    students.studentid=cclogs.newstudentid)
    where course.exampattern='2' 
    group by course.c_id

现在我有三个表,Student、Course 和 CClogs。

我想要的是,课程表中的所有课程,学生表中录取的学生以及cclogs中的学生。但是当我使用这个students.studentid=cclogs.newstudent时,coloum计数(cclogs.newstudent)没有结果。任何想法 ?

这些表是这样的:

课程

C_id   |   Name
 1         Abc
 2         Bcd

学生

Studentid  |   DOA         |   course
   1a        2013-07-05         Abc
   2a        2013-07-05         Bcd
   3a        2013-07-05         Bcd
   4a        2013-07-06         Abc
   5a        2013-07-05         Bcd
   6a        2013-07-06         Abc

记录日志

   id     |    newstudentid     |   oldstudentid   |   DOC      |  newcourse
    1              1b                   1a           2013-07-06      Bcd   
    2              5b                   5a           2013-07-06      Abc

现在,当我运行查询时,假设我想要 2013-07-06 的结果,那么结果应该是:

 Course     |     adm1      |       newstudentid
  Abc              2                      1
  Bcd              1                      1
4

1 回答 1

0

我已经稍微重写了您的查询,以尝试通过给表加上别名,并将应用于连接表(学生和 cclogs)的过滤逻辑从 from 子句移到子查询中,使其更清晰、更容易理解:

select c.course, count(s.studentid) as adm1, count(l.newstudentid) as countNew
from course c
  left join (select * from students where doa = '2013-07-06') s on c.c_id = s.course 
  left join (select * from cclogs where doc = '2013-07-06') l 
    on c.c_id = l.newcid and s.studentid = l.newstudentid
where c.exampattern='2' 
group by c.c_id

现在看看我在这里得到了什么,并将其与您的数据和要求进行比较,仅基于您提供的示例数据,我认为您的查询运行时发生的情况是:

Course 和 Student 之间的连接按预期进行,因为基表(Course)中有行,Student 中有可以与课程相关联的行。但是在加入 ccLogs 时,Students 中没有 newStudentID 存在的行(样本数据中的所有 newStudentID 都是 Bs,而 Student 中的所有 StudentID 都是 As),因此左加入的 ccLogs 只生成空值;

当 select 子句执行时,它在第三列失败,因为对于所有输出行(即 course 表中的每一行),ccLogs 表不返回任何内容,并且查询需要计数为 null。

我认为这个问题可以通过以下方式解决:

select c.course, count(s.studentid) as adm1, 
  sum(case when l.newstudentid is null then 0 else 1 end) as countNew
from course c
  left join (select * from students where doa = '2013-07-06') s on c.c_id = s.course 
  left join (select * from cclogs where doc = '2013-07-06') l 
    on c.c_id = l.newcid and s.studentid = l.newstudentid
where c.exampattern='2' 
group by c.c_id

试试看它是否有效。

希望这可以帮助

于 2013-07-07T23:45:06.343 回答