修改JOIN以按外表中的ID列表过滤结果

时间:2012-09-19 06:48:59

标签: mysql join

这是我的数据库结构:

Observation recording - database structure

我正在使用的SQL语句是:

SELECT
     t1.Name AS Teacher_Name,
     t2.Name AS Observer_Name,
     o.Datetime AS Datetime,
     o.Type AS Type,
     o.Year_Group AS Year_Group,
     o.Class_Name AS Class_Name,
     c.Title AS Course_Name,
     GROUP_CONCAT(DISTINCT l.Title SEPARATOR ', ') AS Focus,
     o.Achievement_Grade AS Achievement_Grade,
     o.Behaviour_Grade AS Behaviour_Grade,
     o.Teaching_Grade AS Teaching_Grade,
     GROUP_CONCAT(DISTINCT cl1.Title SEPARATOR ', ') AS Positive,
     GROUP_CONCAT(DISTINCT cl2.title SEPARATOR ', ') AS Development,
     o.Notes AS Notes
FROM observations o
LEFT JOIN teachers t1 
    ON o.Teacher_ID = t1.Teacher_ID
LEFT JOIN teachers t2 
    ON o.Observer_ID = t2.Teacher_ID
LEFT JOIN courses c 
    ON o.Course_ID = c.Course_ID
LEFT JOIN  foci f
    ON o.ID = f.Observation_ID
LEFT JOIN focus_labels l
    on f.focus_id = l.id
LEFT JOIN  criteria c1
    ON o.ID = c1.Observation_ID
LEFT JOIN criteria_labels cl1
    on c1.Criteria_ID = cl1.ID AND c1.Type = 'P'
LEFT JOIN  criteria c2
    ON o.ID = c2.Observation_ID AND c2.Type = 'D'
LEFT JOIN criteria_labels cl2
    on c2.Criteria_ID = cl2.ID
GROUP BY o.id
ORDER BY Datetime DESC

从这样的结果集返回的数据是:

Observation Recording - List of observations results


我现在想要实现的是课程的搜索。

我的输入是一个ID列表,所以我希望我可以使用类似的东西:

SELECT * FROM Courses WHERE Course_ID IN (1, 2, 3, 4)

显然,这并不是那么简单,因为我的Courses正在加入:

LEFT JOIN courses c ON o.Course_ID = c.Course_ID

我如何修改此声明以包含此类搜索功能?

提前致谢,

1 个答案:

答案 0 :(得分:1)

为什么不呢?只需添加到您的查询where声明:

.............................
LEFT JOIN criteria_labels cl2
    on c2.Criteria_ID = cl2.ID
WHERE o.Course_ID IN (1, 2, 3, 4)
GROUP BY o.id
ORDER BY Datetime DESC