2012-01-09 14 views
4

假設我有一個烹飪節目:相對於一個串聯行JOIN

cookingepisodes 
id | date 
--------------- 
1 | A 
2 | B 
3 | C 
4 | D 
… 

這個節目審查的產品在這些類別(左)和圖表鏈接到正確的:

tests    testitems 
id | name   id | episodeid | testid | name 
------------  ------------------------------------ 
1 | cutlery  1 | 1   | 1  | Forks 
2 | spices   2 | 2   | 1  | Knives 
        3 | 4   | 1  | Spoons 
        4 | 4   | 2  | Oregano 

我的期望輸出是這樣的:

showid | testid | testname 
    4 | 1,2 | cutlery, spices 
    3 | NULL | NULL 
    2 | 1  | cutlery 
    1 | 1  | cutlery 

我試着使用這個查詢,只要我不需要連接結果(當在同一集中有兩個測試時),它就會工作。然後加入基於我也試着像這樣的

SELECT DISTINCT e.*, i.testid, t.name AS testname 
FROM cookingepisodes AS e 
LEFT OUTER JOIN testitems AS i ON i.episodeid = e.id 
LEFT OUTER JOIN tests AS t ON i.testid = t.id 
ORDER BY e.date DESC 

數量將創建多個行,但我不能讓它因爲外塊參照工作(e.id):

JOIN (
    SELECT GROUP_CONCAT(DISTINCT testid) 
    FROM testitems 
    WHERE testitems.episodeid = e.id 
) AS i 

有關如何在不重構數據庫的情況下解決此問題的任何提示?

回答

6

嘗試這一個 -

SELECT 
    ce.id showid, 
    GROUP_CONCAT(te.testid) testid, 
    GROUP_CONCAT(t.name) testname 
FROM cookingepisodes ce 
    LEFT JOIN testitems te 
    ON te.episodeid = ce.id 
    LEFT JOIN tests t 
    ON t.id = te.testid 
GROUP BY 
    ce.id DESC; 
+0

完美!我試過這個,但是我沒有'GROUP BY',所以我想這是我的問題。非常感謝! – Eikern 2012-01-11 12:11:45