2012-09-18 40 views
0

這裏是我的數據庫結構:使用GROUP_CONCAT檢索來自外部表的標題列表

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(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.Observation_ID是否滿足Observations.ID然後檢索每個重點從Focus_Labels.Title的名字,如果Foci.Focus_ID匹配Focus_Labels.ID焦點表中檢索每一行實現。

在上面的聲明中,我沒有得到儘可能檢索Focus_Labels.Title,因爲我甚至無法獲得Foci.ID的工作。

任何人都可以幫忙嗎?

+0

我想你需要一個'GROUP BY'使用'GROUP_CONCAT' – HerrSerker

+0

@dunc如果你用表和一些示例數據創建了一個[SQL Fiddle](http://sqlfiddle.com/)會很有幫助。 – Taryn

回答

1

我建議從INNER JOINLEFT 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 
+0

美麗,謝謝。對不起,我不能按照你的建議去做SQL小提琴,Ofsted明天就要到了,我正在瘋狂衝刺! – dunc

+0

@dunc很高興它工作,我只是建議一個SQL小提琴。這有助於查看您的數據,然後生成您所需的結果。 – Taryn