我一直坚持建立查询,即计算特殊情况的出现次数
我有:
teachers {id, email, first_name, last_name,...}
faculties {id, name}
pupils {id, name, teacher_id} //every pupil has their own curator
faculties_teachers {id, teacher_id, faculty_id}
查询尝试检查数据的完整性。应该没有重复。
我需要查询每位教师的学生数量。
这个查询工作得非常好,直到我添加了我的计算每个学院的不同学生的数量(在我的情况下确实是独一无二的))
SELECT u1.id, u2.id, u1.owner, u2.owner, u1.email, u1.first_name, u2.last_name, u1.name_of_site, faculties_teachers.faculty_id, faculties.name,
(SELECT COUNT( pupils.* ) FROM pupils as p WHERE faculties.id = pupils.faculty_id)
FROM `teachers` AS u1
JOIN `teachers` AS u2 ON u1.email = u2.email
JOIN `faculties_teachers` AS ft ON u1.id = ft.teacher_id
JOIN `faculties` ON faculties.id = ft.faculty_id
JOIN `pupils` ON faculties.id = pupils.faculty_id
WHERE u1.id < u2.id
ORDER BY `u1`.`id` ASC
答案 0 :(得分:0)
呵呵 - 感谢我的同事
SELECT u1.id, u2.id, u1.owner, u2.owner, u1.email, u1.first_name, u2.last_name, u1.name_of_site, faculties_teachers.faculty_id, faculties.name, COALESCE(pupil_counts_by_faculties.pupil_cnt, 0) AS pupil_cnt
FROM `teachers` AS u1
JOIN `teachers` AS u2 ON u1.email = u2.email
JOIN `faculties_teachers` ON u1.id = faculties_teachers.urid
JOIN `faculties` ON faculties.id = faculties_teachers.faculty_id
LEFT JOIN (
SELECT `faculty_id`, COUNT(*) AS pupil_cnt
FROM `pupils`
GROUP BY `faculty_id`
) AS pupil_counts_by_faculties ON `faculties`.`id` = pupil_counts_by_faculties.faculty_id
WHERE u1.id < u2.id