如何使用MySQL在单个查询中对来自1-many关系的数据进行分组?

时间:2017-12-09 23:25:12

标签: mysql sql

我有3个表,食谱 recipes_instructions recipes_ingredients ,第一个是主要的,其余的是指 recipe_id 来自食谱表格。

我编写下面的代码试图让一些工作正常,现在它正在检索我想要的所有数据,我只是不确定如何通过它的组来组织它,我认为 GROUP_CONCAT 是要走的路,但不知道如何去做。

这是我想要的结果:

Array
(
    [id] => 1
    [title] => Citrus Shortbread Cookies
    [instruction_group] => Array (
        [0] => Divide the dough into 2 equal portions...
        [1] => Preheat an oven to...
        [2] => Remove wax paper, and...
        [3] => Bake in the preheated oven...
    )
    [ingredients_group] => Array (
        [0] => 1 cup (230g) butter
        [1] => 1 teaspoon vanilla extract
        [2] => 2 cups (250g) all-purpose flour
        [3] => Zest of one lime
        [4] => 1/2 cup (65g) icing sugar
    )
)

我尝试了什么:

1:这是我得到的最接近的东西,它仍然有重复的结果,它甚至从未指定的配方ID中检索数据库中的所有数据。

http://sqlfiddle.com/#!9/725468/33

SELECT *
  FROM recipes 
INNER JOIN
  (SELECT recipe_id, GROUP_CONCAT(instruction) instruction_group FROM recipe_instructions) 
  as instructionscombined 
  on recipes.id = instructionscombined.recipe_id
INNER JOIN 
  (SELECT recipe_id, GROUP_CONCAT(ingredients) ingredient_group FROM recipe_ingredients)
  as ingredientscombined
  on recipes.id = ingredientscombined.recipe_id
WHERE recipes.id = 1

2:结果重复,表中的所有数据都已从未指定配方ID的数据中返回。

http://sqlfiddle.com/#!9/725468/39

SELECT *, GROUP_CONCAT(inst.instruction), GROUP_CONCAT(ingr.ingredients) FROM recipes 
INNER JOIN recipe_instructions as inst on recipes.id = inst.recipe_id
INNER JOIN recipe_ingredients as ingr on recipes.id = ingr.recipe_id
WHERE recipes.id = 1

修改 至于查询返回行的所有数据的问题是因为我在嵌套选择中没有显式。

这解决了问题,但我仍然得到重复的recipe_id列

http://sqlfiddle.com/#!9/725468/64

SELECT *
  FROM recipes 
INNER JOIN
  (SELECT recipe_id, GROUP_CONCAT(instruction) instruction_group 
   FROM recipe_instructions
   WHERE recipe_id = 1
  )
  as instructionscombined 
  on recipes.id = instructionscombined.recipe_id
INNER JOIN 
  (SELECT recipe_id, GROUP_CONCAT(ingredients) ingredient_group 
   FROM recipe_ingredients
   WHERE recipe_id = 1
  )
  as ingredientscombined
  on recipes.id = ingredientscombined.recipe_id
WHERE recipes.id = 1
GROUP BY recipes.id

第二次编辑:

所以......我学到的是mysql没有数组功能,所以我现在正在做的是使用上面的查询,并使用 GROUP_CONCAT分离group_concat(说明SEPARATOR \ '__ \')(我不得不逃避'因为我正在使用php),然后运行一个while循环并爆炸组。

1 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT 
    a.*,
    GROUP_CONCAT(DISTINCT b.instruction ORDER BY b.instruction_id) as `instructions`,
    GROUP_CONCAT(DISTINCT c.ingredients ORDER BY c.ingredient_id) as `ingredients`
FROM recipes a
JOIN recipe_instructions b
ON a.id = b.recipe_id
JOIN recipe_ingredients c
ON a.id = c.recipe_id
GROUP BY a.id
ORDER BY a.title

以下是此查询的SQL Fiddle