[英]Counting multiple columns in one query
Say I have the following tables, 说我有以下表格,
lesson 课
id description
-----------------
1 science
2 english
3 maths
lesson_student_rel lesson_student_rel
lesson_id student_id
----------------------
1 1
1 2
1 3
2 1
3 1
3 3
lesson_tutor_rel lesson_tutor_rel
lesson_id tutor_id
--------------------
1 1
2 1
2 2
lesson_assistant_rel lesson_assistant_rel
lesson_id assistant_id
------------------------
1 1
1 2
3 2
I would like to count the total number of students, tutors and assistants for each lesson so I get a result like, 我想计算每节课的学生,导师和助手的总数,这样我得到的结果是,
lesson_id student_count tutor_count assistant_count
---------------------------------------------------------
1 3 1 2
2 1 2 0
3 2 0 1
I think I've been looking at this too long now and have got completely stuck, I've found a few similar questions but nothing that seems to answer this. 我想我已经看了太久了,已经完全陷入困境,我发现了一些类似的问题,但是似乎没有答案。 Is it possible to do with one query?
是否可以处理一个查询? Any pointers would be good - an answer would be amazing.
任何指针都是好的-答案将是惊人的。
Thanks! 谢谢!
I think this does it for you: 我认为这为您做到了:
SELECT l.id,COUNT(DISTINCT lsr.student_id) student_count,COUNT(DISTINCT ltr.tutor_id) tutor_count
,COUNT(DISTINCT lar.assistant_id) assistant_count
FROM lesson l
LEFT JOIN lesson_student_rel lsr ON lsr.lesson_id=l.id
LEFT JOIN lesson_tutor_rel ltr ON ltr.lesson_id=l.id
LEFT JOIN lesson_assistant_rel lar ON lar.lesson_id=l.id
GROUP BY l.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.