SQL Query,多个左连接和嵌套查询的Group_Concat

时间:2015-10-20 22:22:36

标签: sql sqlite

我正在玩sql,在互联网上玩教程,在应用程序中使用一些基本的sqlite,并且遇到了以下问题。

我有几个表格如下所述。

表1(配方)

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

表2(方法)

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

表3(成分)

SELECT Recipe.* FROM Recipe

我基本上想要做的是打印出一份食谱清单,所有可能的方法以及这些方法中的所有成分。如果没有列出的indigents或方法,只显示null或为空。

第1步:

id  name
1   Carrot Cake
2   Cheese Cake
3   Chocolate Cake

显然打印出来

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

第2步:

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 (.... )

这又有意义,但是现在我想列出每种方法的成分和数量,比如

{{1}}

格式不一定相同,只是显示相同的信息,不知何故

有一个快速谷歌,我遇到'嵌套查询',但我正在努力让它们工作

非常感谢任何指导

由于

1 个答案:

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

此结果集类似于您在其上执行外部查询的表。