我对 SQL 还是很陌生,我还没有完全理解我的代码中的问题来自哪里。下面的代码主要来自我的工作,所以我不是从头开始编写的。该代码收集了一堆不同的信息并基于它进行过滤。如果您查看代码,您会看到一个学生有许多与之相关的observations_students。代码的第一个版本返回所有具有observation_student 的学生的信息,observation_id = 2567。这似乎与以下代码一起正常工作:
SELECT DISTINCT
SUBSTRING(s.osis_id,INSTR(s.osis_id,'-')+1) AS osid,
s.id AS student_id,
CONCAT(s.last_name, ' ',s.first_name) AS sname
FROM students s
# course info
INNER JOIN
(
SELECT c.id AS cid,
c.description AS cname,
cs.date_end,
cs.student_id,
gl.description AS grade,
c.gradelevel_id
FROM courses_students cs
INNER JOIN courses c ON c.id = cs.course_id
INNER JOIN gradelevels gl ON gl.id = c.gradelevel_id
WHERE
IFNULL(cs.date_end, NOW()) >= NOW()
AND IFNULL(c.date_end, NOW()) >= NOW()
AND c.school_id = 1509
AND c.subject_id = 24
) AS cs ON cs.student_id = s.id
# RTI flag info
INNER JOIN
(
SELECT os.id,
os.student_id
FROM observations o
INNER JOIN observations_students os ON os.observation_id = 2567
WHERE
o.school_id = 1509
) AS os ON os.student_id = s.id
LEFT JOIN schools_students ss ON ss.student_id = s.id
WHERE s.active = 1
AND ss.school_id = 1509
AND IFNULL(ss.date_end,NOW()) >= NOW()
AND cs.gradelevel_id BETWEEN 10 AND 16
在此之后我想做的是对于每个有 2567 观察的学生,我想找到学生拥有的 2009 观察的数量。为此,我添加了另一个 LEFT JOIN,完成的代码如下所示:
SELECT DISTINCT
SUBSTRING(s.osis_id,INSTR(s.osis_id,'-')+1) AS osid,
s.id AS student_id,
CONCAT(s.last_name, ' ',s.first_name) AS sname,
COUNT(fdos.id) AS fd_count
FROM students s
# course info
INNER JOIN
(
SELECT c.id AS cid,
c.description AS cname,
cs.date_end,
cs.student_id,
gl.description AS grade,
c.gradelevel_id
FROM courses_students cs
INNER JOIN courses c ON c.id = cs.course_id
INNER JOIN gradelevels gl ON gl.id = c.gradelevel_id
WHERE
IFNULL(cs.date_end, NOW()) >= NOW()
AND IFNULL(c.date_end, NOW()) >= NOW()
AND c.school_id = 1509
AND c.subject_id = 24
) AS cs ON cs.student_id = s.id
# RTI flag info
INNER JOIN
(
SELECT os.id,
os.student_id
FROM observations o
INNER JOIN observations_students os ON os.observation_id = 2567
WHERE
o.school_id = 1509
) AS os ON os.student_id = s.id
LEFT JOIN
(
SELECT fdos.id,
fdos.student_id
FROM observations o
INNER JOIN observations_students fdos ON fdos.observation_id = 2009
WHERE
o.school_id = 1509
) AS fdos ON fdos.student_id = s.id
LEFT JOIN schools_students ss ON ss.student_id = s.id
WHERE s.active = 1
AND ss.school_id = 1509
AND IFNULL(ss.date_end,NOW()) >= NOW()
AND cs.gradelevel_id BETWEEN 10 AND 16
如果我将“COUNT(fdos.id) AS fd_count”更改为“fdos.id AS fdosid”,则会返回正确的条目数。但是,从 COUNT 返回的数字不是同一个数字,也不正确。谁能理解这里发生的事情足以解释我做错了什么?
感谢您的时间。