2013-07-07 54 views
-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 

现在我有三个表,学生,课程和CClogs。

我想要的是,课程表中的所有课程,在学生表中以及cclogs中录取的学生。但是当使用这个students.studentid = cclogs.newstudent时,coloum count(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 

CClogs

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 
+1

不确定它是否相关,但不需要'DISTINCT'修饰符。 'GROUP BY course.c_id'应该这样做。 – Barmar

+0

您可以添加一些示例数据和期望的结果,并制作一个我们可以尝试的sqlfiddle? – Barmar

+0

你能提供一些样本数据和你想要的结果吗?这也有助于解释为什么这是不正确的。 –

回答

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 

现在看看我在这里得到了什么,并将它与您的数据和要求,只是样本数据的基础上,你给,我的想法是当您的查询运行时发生的是这样的:

“课程”与“学生”之间的连接按预期发生,因为基础表(课程)中有行,学生中可以与课程相关的行也是如此。但是,加入ccLogs时,学生中不存在newStudentID存在的行(示例数据中的所有newStudentID均为Bs,而学生中的所有StudentID均为As),因此左侧加入的ccLog只生成空值;

当select子句执行时,第三列失败,因为对于所有输出行(即课程表中的每一行),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 

尝试一下,看看它是否工作。

希望这会有帮助