我在数组中有一组大约9000个教师ID,我把它们放在一个字符串中:
(1,2, 3, 4,5,6,7,....9000,9001,9002)
以便我可以在以下查询中使用它们:
select count(student_assignment.assignment_id) as total_assignment from
student_assignment, assigned_tutor_fk where assignment_status = 'closed'
and assigned_tutor_fk in (1,2, 3, 4,5,6,7,..100,101,103...9000,9001,9002)
group by assigned tutor_fk.
我想计算与每位导师相关的总行数(assigned_tutor_fk),以及那些没有作业的导师,即那些没有作业的导师 记录在表中我想显示他们的分配计数为0,我只想让我的查询返回计数和assigned_tutor_fk 我的表结构是:
assignment_id | assigned_tutor_fk | assignment_date | student_id |
| 1 | 2 | 22-01-2011 | 4 |
| 2 | 3 | 14-03-2011 | 5 |
我试图让我的输出像这样:
|total_assignment | assigned_tutor_fk |
| 5 | 4 |
| 2 | 7 |
| 0 | 8 |
更新:我认为我无法正确表达自己,我已经有一个按照其他标准过滤的导师列表,结合这两个查询非常复杂所以现在我有一套导师id和我如果导师没有作业记录,希望总和显示为零。请帮助我,因为我不知道现在要做什么
答案 0 :(得分:2)
SELECT t.id, COUNT(sa.assignment_id)
FROM tutor t
LEFT JOIN
student_assignement sa
ON sa.assignment_tutor_fk = t.id
WHERE t.id IN (1, 2, ..., 9002)
GROUP BY
t.id
答案 1 :(得分:1)
SELECT
count(*) as total_assignment,
assigned_tutor_fk
FROM assignmentTable
GROUP BY assigned_tutor_fk
答案 2 :(得分:0)
不要把导师放在一个字符串中。从表中选择它们并使用赋值和FK表执行LEFT JOIN。在不知道你所有的桌子的情况下,我猜它会是这样的:
select
t.tutorId,
count(sa.assignment_id) as total_assignment
from
tutor t
LEFT JOIN
assigned_tutor_fk fk
ON
fk.assigned_tutor_fk = tutor.tutorId
LEFT JOIN
student_assignment sa
ON
fk.assignment_id = sa.id
where
sa.assignment_status = 'closed' OR
ISNULL(sa.assignment_status) -- if join fails.
group by
t.tutorId
Left Join
从教师表中检索所有值,并在匹配时将其与联接表合并。如果不是,则插入NULL。