我发现,你可以将它们分解的时间,一步意义的事情。
首先,让我们抓住我们的甜点。
SELECT categories.cid
FROM categories
WHERE category_name = 'desserts'
现在让我们通过在结果的左侧粘贴沙漠食谱来抓取所有食谱。对于类别中的每个匹配行,recipe_categories中可以有一个或多个匹配行。对于recipe_categories中的每个匹配行,配方中可以有一个或多个匹配的行。
SELECT categories.cid, recipes.recipe_name
FROM categories
LEFT JOIN recipe_categories ON (recipe_categories.category_id = categories.cid)
LEFT JOIN recipes ON (recipes.rid = recipe_categories.recipe_id)
WHERE category_name = 'desserts'
最后,让我们把我们的成分附在左边。对于我们目前为止的每一个匹配行(我们现在都在食谱中),我们可以在recipe_ingredients中有一个或多个匹配,然后在配方中再次匹配一个或多个匹配。
SELECT recipes.recipe_name, ingredients.ingredient_name
FROM categories
LEFT JOIN recipe_categories ON (recipe_categories.category_id = categories.cid)
LEFT JOIN recipes ON (recipes.rid = recipe_categories.recipe_id)
LEFT JOIN recipe_ingredients ON (recipe_ingredients.recipe_id = recipes.rid)
LEFT JOIN ingredients ON (ingredients.iid = recipe_ingredients.ingredient_id)
WHERE category_name = 'desserts'
到目前为止我还在吗?
现在,它已经晚了,我还没有测试过这个,但它应该返回你正在查找的数据。实际上,我可能完全使用错误的连接类型来正确完成此操作。我敢肯定,如果我错了,评论中有人会纠正我。
这是什么不会做的是返回数据格式如你所愿。让我们对查询进行最后一次迭代以添加一些id字段。
SELECT recipes.rid, recipes.recipe_name, ingredients.iid, ingredients.ingredient_name
FROM categories
LEFT JOIN recipe_categories ON (recipe_categories.category_id = categories.cid)
LEFT JOIN recipes ON (recipes.rid = recipe_categories.recipe_id)
LEFT JOIN recipe_ingredients ON (recipe_ingredients.recipe_id = recipes.rid)
LEFT JOIN ingredients ON (ingredients.iid = recipe_ingredients.ingredient_id)
WHERE category_name = 'desserts'
让我们把数据收集到一个多维数组中。假设我们正在使用PDO。
$query = '...';
$sh = $db->prepare($query);
$sh->execute();
$recipes = array();
while($row = $sh->fetch(PDO::FETCH_ASSOC)) {
// For each row in the result set, check to see if we've looked at this recipe.
if(!array_key_exists($row['rid'], $recipes)) {
// If we haven't, let's initialize the row with the recipe name
// and a place to stick each ingredient.
$recipes[ $row['rid'] ] = array(
'recipe_name' => $row['recipe_name'],
'ingredients' => array()
);
}
// Place this ingredient with the proper recipe.
$recipes[ $row['rid'] ]['ingredients'][ $row['iid'] ] = $row['ingredient_name'];
}
结果应该是这样的:
array(
1 => array(
'recipe_name' => 'black forest cake',
'ingredients' => array(
'1' => 'self-raising flour',
'2' => 'milk',
...
)
)
)
从这个结构,你可以做你想做的。
分隔。非常感谢! – circey 2010-07-20 05:17:19