在多个字段上使用GROUP_CONCAT

时间:2012-09-18 19:50:23

标签: mysql

以下是我的数据库结构图:

Observation recording - database structure

在这里的用户的帮助下,我设法使用GROUP_CONCAT整理了一个非常复杂的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(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";

除了根据连接数最多的字段重复FocusPositiveDevelopment这一事实外,这似乎还可以。

例如,如果PositivePace,Progress,AttainmentFocus仅为Appraisal,则会重复三次(Appraisal,Appraisal,Appraisal)。

Observation Recording - Complex join structure

我看了这个,我认为可能是因为我需要GROUP这些GROUP_CONCAT JOINs。但是,我不知道如何解决这个问题。

有人可以帮忙吗?提前谢谢,

1 个答案:

答案 0 :(得分: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";