0

这是我的数据库结构:

观察记录 - 数据库结构

这是我正在尝试的 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(f.Focus_ID) AS Focus,
 o.Achievement_Grade AS Achievement_Grade,
 o.Behaviour_Grade AS Behaviour_Grade,
 o.Teaching_Grade AS Teaching_Grade,
 o.Notes AS Notes
FROM observations o
INNER JOIN teachers t1 ON o.Teacher_ID = t1.Teacher_ID
INNER JOIN teachers t2 ON o.Observer_ID = t2.Teacher_ID
INNER JOIN courses c ON o.Course_ID = c.Course_ID
INNER JOIN foci f ON f.Observation_ID = o.ID
ORDER BY `Datetime` DESC LIMIT 0,10

我想要实现的是,在上述语句中,检索Foci带有,分隔符的列表,例如Appraisal,Post 16,Teaching and Learning.

这可以通过检索Foci 表中 Foci.Observation_ID 与 Observations.ID 相遇的每一行来实现 ,然后 如果 Foci.Focus_ID 与 Focus_Labels.ID 匹配,则从 Focus_Labels.Title 检索每个焦点的名称

在上面的声明中,我没有尝试检索Focus_Labels.Title,因为我什至无法Foci.ID正常工作。

任何人都可以帮忙吗?

4

1 回答 1

1

我建议从 an 稍微更改INNER JOIN为 aLEFT JOIN因为除非您确定所有表中都存在某些行,否则您将不会返回结果:

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(l.title) AS Focus,
     o.Achievement_Grade AS Achievement_Grade,
     o.Behaviour_Grade AS Behaviour_Grade,
     o.Teaching_Grade AS Teaching_Grade,
     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
GROUP BY o.id
ORDER BY `Datetime` 
DESC LIMIT 0,10
于 2012-09-18T19:16:24.043 回答