0

这是我的数据库结构的图片:

观察记录——数据库结构

在此处用户的帮助下,我设法使用以下方法组合了一个相当复杂的 SQL 语句GROUP_CONCAT

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,
     GROUP_CONCAT(cl1.Title) AS Positive,
     GROUP_CONCAT(cl2.title) 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";

这似乎工作正常,除了Focus,PositiveDevelopment每个都根据具有最多连接数的字段重复。

例如,如果Positivehas Pace,Progress,Attainmentbut Focusis only Appraisal,它将重复 3 次 ( Appraisal,Appraisal,Appraisal)。

观察记录 - 复杂的连接结构

我已经查过了,我认为这可能是因为我需要这些中的GROUP每一个GROUP_CONCAT JOINs。但是,我不知道该怎么做。

任何人都可以帮忙吗?提前致谢,

4

1 回答 1

1

GROUP_CONCAT具有可用于删除重复项的 DISTINCT 属性。

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) AS Focus,
     o.Achievement_Grade AS Achievement_Grade,
     o.Behaviour_Grade AS Behaviour_Grade,
     o.Teaching_Grade AS Teaching_Grade,
     GROUP_CONCAT(cl1.Title) AS Positive,
     GROUP_CONCAT(cl2.title) 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";
于 2012-09-18T19:52:51.433 回答