0

我有三个表:用户、课程、注册。Enrollments 表是具有外键的表,因此我可以分别进行联接:users.pk1 =enrollments.u_pk1 和 course.pk1 =enrollments.c_pk1。用户表包含教授和学生。到目前为止,一切都很好!

我要做的是生成名称为字符串 2013 的所有课程的列表,然后获取每门课程的所有教授,最后从只有以下内容的 Enrollment 表中获取每门课程中所有学生的计数列: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

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

4

2 回答 2

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;

但是,第二个查询可能比第一个查询慢得多。

于 2013-09-01T00:36:37.610 回答
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
于 2013-08-31T23:40:28.770 回答