如何计算SQL子查询

时间:2013-08-31 23:15:40

标签: sql

我有三个表:用户,课程,注册。 Enrollments表是具有外键的表,因此我可以分别创建Joins:users.pk1 = enrollments.u_pk1和courses.pk1 = enrollments.c_pk1。 Users表包含教授和学生。到目前为止一切顺利!

我要做的是生成所有课程名单中包含2013年字符串的列表,然后抓住每门课程的所有教授,最后从入学表中获取每门课程中所有学生的计数有以下列:pk1,c_pk1,u_pk1,角色。

这是我想要做的,但它显然不起作用,因为Count不接受子查询作为参数:

select c.name, u.name, count(select * from enrollments where role = 'student') 
from courses c, users u, enrollments e
where u.pk1 = e.u_pk1 and c.pk1 = e.c_pk1 
and c.name like '%2013%' and e.role = 'professor'
order by c.name;

关于如何以我想要的方式完成这项工作的任何提示?

...

稍后编辑: 使用Trogdor的解决方案,我能够从计数的角度来看它的工作原理,但现在我仍然坚持如何只列出一个课程,然后列出一行中所有教授的名字。例如,有这样的事情:

course1 prof1 13
course1 prof2 13
course2 prof3 25

它应该看起来像:

course1 prof1,prof2 13
course2 prof3 25

等等...有关如何实现这一目标的任何提示?

2 个答案:

答案 0 :(得分:1)

试试这个:

select c.name, u.name, x.total
from courses c, users u, enrollments e, 
    (select c_pk1, count(*) as total 
     from enrollments 
     where role='student' 
     group by c_pk1) x
where u.pk1 = e.u_pk1 and c.pk1 = e.c_pk1 
and c.name like '%2013%' and e.role = 'professor' and c.pk1 = x.c_pk1
order by c.name;

您还可以在选择中使用相关子查询:

select c.name, u.name, 
    (select count(*) from enrollments e2 
      where e2.role = 'student' and e2.c_pk1 = c.pk_1) 
from courses c, users u, enrollments e
where u.pk1 = e.u_pk1 and c.pk1 = e.c_pk1 
and c.name like '%2013%' and e.role = 'professor'
order by c.name;

然而,第二个查询可能明显慢于第一个查询。

答案 1 :(得分:0)

我会这样做。更明确。没有办法测试这个,很抱歉,如果有错误。但它应该给你一个想法。

select c.name, p.name, count(*)
from courses c
join enrollments e on e.c_pk1 = c.pk1
join users p on p.pk1 = e.u_pk1 and e.role = 'professor'
join users s on s.pk1 = e.u_pk1 and e.role = 'student'
where c.name like '%2013%'
group by c.name, p.name
order by c.name, p.name