[英]Mysql Count to return zero if no match
I have a set of approx 9000 tutor ids in an array and i have put them in a string like: 我在数组中有一组大约9000个教师ID,并且已将它们放在类似以下的字符串中:
(1,2, 3, 4,5,6,7,....9000,9001,9002)
so that i can use them in the following query: 这样我就可以在以下查询中使用它们:
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.
I want to calculate total number of rows associated with each tutor(assigned_tutor_fk), and those tutors which do not have an assignment ie those which do not have assignment record in the table i want to show their assignment count as 0, and i just want my query to return count and assigned_tutor_fk my table structure is: 我想计算与每个导师(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 |
Im trying to get my output to be like this: 我试图让我的输出是这样的:
|total_assignment | assigned_tutor_fk |
| 5 | 4 |
| 2 | 7 |
| 0 | 8 |
Update: I tthink i have not been able to express myself properly,i already have a list of tutors filtered on another criteria, it was very complex to combine these two queries so now i have a set of the tutor id's and i want the sum to be displayed as zero in case the tutors does not have assignment record. 更新:我想我无法正确表达自己,我已经有一个根据其他条件过滤的导师列表,将这两个查询结合起来非常复杂,所以现在我有了一组导师ID,我想要总和如果导师没有作业记录,则显示为零。 please help me on this as i don know wht to do now
请帮助我,因为我现在不知道该怎么做
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
SELECT
count(*) as total_assignment,
assigned_tutor_fk
FROM assignmentTable
GROUP BY assigned_tutor_fk
dont put the tutors in a string. 不要把老师串成一串。 Select them from a table and do a LEFT JOIN with the assignment and FK table.
从表中选择它们,然后对作业和FK表进行左联接。 Without knowing all of your tables, i'm guessing it would look like this:
在不知道您所有表的情况下,我猜它看起来像这样:
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
retrieves all your values from the tutor table and merges it with the joined table IF there is a match. 如果存在匹配项,则“
Left Join
将从导师表中检索所有值并将其与联接表合并。 If not, NULL is inserted. 如果不是,则插入NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.