2015-10-20 137 views
2

我在玩弄sql,在互聯網上玩教程,在應用中使用一些基本的sqlite,並且遇到以下問題。多個左連接和嵌套查詢的SQL查詢,Group_Concat

我有幾個表如下所述。

表1(配方)

ID,  Name 
1,  Carrot Cake 
2,  Cheese Cake 
3,  Chocolate Cake 

表2(方法)

ID,  Method Name,   RecipeID 
1,  Old School Method, 1 
2,  Low Salt Method,  1 
3,  Extra Chocolate,  3 

表3(配料)

ID,  Name,  Quantity, MethodID 
1,  Eggs,  2,   1 
2,  Carrots, 1,   1 
3,  Flour,  40,   1 
4,  Salt,  2,   1 
5,  Eggs,  2,   2 
6,  Carrots, 1,   2 
7,  Flour,  50,   2 
8,  Milk,  20,   3 
9,  Chocolate, 10,   3 
10,  Eggs,  1,   3 

我基本上想要做的是打印出配方列表,所有可能的方法以及這些方法中的所有成分。如果沒有列出的貧困人羣或方法,只顯示空白或空白。

步驟1:

SELECT Recipe.* FROM Recipe 

明顯打印出

id name 
1 Carrot Cake 
2 Cheese Cake 
3 Chocolate Cake 

步驟2:

SELECT Recipe.*, GROUP_CONCAT(Method.Name) as Methods 
FROM Recipe 
LEFT JOIN Method 
ON Method.RecipeID = Recipe.ID 
GROUP BY Recipe.id 

返回

id name   Methods 
1 Carrot Cake  Low Salt Method,Old School Method 
2 Cheese Cake  (null) 
3 Chocolate Cake Extra Chocolate 

這又是有道理的,但是現在我想列出每種方法的成分和數量,像

1 Carrot Cake Low Salt Method (Eggs 2, Carrots 1, Flour 40, Salt 2), Old School Method (....) 

格式還沒有得到是相同的,但只顯示同樣的信息,不知何故

有一個快速谷歌,我碰到「嵌套查詢」但是我努力使他們的工作

任何指導,將衷心感謝

感謝

回答

2

您需要分兩步分組數據:第一個成分,下一個方法。 這需要一個子查詢:

select id, recipename, group_concat(name || ' ' || ingredients) 
from (
    select 
     r.id, r.recipename, m.name, 
     '(' || group_concat(i.name || ' ' || i.quantity, ',') || ')' ingredients 
    from recipe r 
    left join method m on m.recipeid = r.id 
    left join ingredients i on i.methodid = m.id 
    group by 1, 2, 3 
    ) sub 
group by 1, 2; 

1 | Carrot Cake | Low Salt Method (Carrots 1, Eggs 2, Flour 50), Old School Method (Carrots 1, Eggs 2, Flour 40, Salt 2) 
2 | Cheese Cake | 
3 | Chocolate Cake| Extra Chocolate (Chocolate 10, Eggs 1, Milk 20) 

爲了更好地理解它是如何工作的,運行內部查詢:

select 
     r.id, r.recipename, m.name, 
     '(' || group_concat(i.name || ' ' || i.quantity, ',') || ')' ingredients 
    from recipe r 
    left join method m on m.recipeid = r.id 
    left join ingredients i on i.methodid = m.id 
    group by 1, 2, 3; 

1 | Carrot Cake | Low Salt Method | (Carrots 1, Eggs 2, Flour 50) 
1 | Carrot Cake | Old School Method | (Carrots 1, Eggs 2, Flour 40, Salt 2) 
2 | Cheese Cake |     | 
3 | Chocolate Cake| Extra Chocolate | (Chocolate 10, Eggs 1, Milk 20) 

此結果集是一樣的,你執行外查詢的表。