我目前的代码是:
$select = $this->select()
->from(array('r' => 'recipes'), $this->getAdapter()
->quoteInto("r.*, MATCH(title, directions) AGAINST(?) AS score", $searchText))
->where('MATCH(title, directions) AGAINST(?)', $searchText);
//SQL: SELECT r.*, MATCH(title, directions) AGAINST('chicken soup') AS `score` FROM `recipes` AS `r` WHERE (MATCH(title, directions) AGAINST('chicken soup'))
我想添加一个额外的WHERE子句来仅查找包含某种成分的食谱。我遇到的问题来自于成分表和我的食谱表有多个 - 多关系,连接表ingredient_recipes,其列有'id','recipe_id'和'ingredient_id'。
我该怎么做?
答案 0 :(得分:0)
这是按成分搜索食谱的简单SQL。你可以从那里推断细节。
SELECT r.*
FROM recipes r
LEFT OUTER JOIN recipe_ingredients ri ON r.recipe_id = re.recipe_id
LEFT OUTER JOIN ingredients i on ri.ingredient_id = i.ingredient_id
WHERE i.ingredient_title = "[Your Ingredient Variable]"
GROUP BY r.recipe_id;
对于多种成分:
SELECT r.*
FROM recipes r
LEFT OUTER JOIN recipe_ingredients ri ON r.recipe_id = re.recipe_id
LEFT OUTER JOIN ingredients i on ri.ingredient_id = i.ingredient_id
WHERE i.ingredient_title = "[First Ingredient Var]"
OR i.ingredient_title = "[Second Ingredient Var]"
GROUP BY r.recipe_id;
虽然如果你试图找到同时存在的东西(不只是一个或另一个),你可能需要做两个查询(或者至少是一个子选择),这可能是一个很慢的查询大型数据库。
我能想到的最好的单个查询就是这样的:
SELECT r.*
FROM recipes r
LEFT OUTER JOIN recipe_ingredients ri ON r.recipe_id = re.recipe_id
LEFT OUTER JOIN ingredients i1 on ri.ingredient_id = i1.ingredient_id
LEFT OUTER JOIN ingredients i2 on ri.ingredient_id = i2.ingredient_id
WHERE i1.ingredient_title = "[First Ingredient Var]"
AND i2.ingredient_title = "[Second Ingredient Var]"
GROUP BY r.recipe_id;
您为每个其他成分创建另一个联接的位置。这个查询不会返回含有一些(但不是全部)成分的食谱,只有具有您正在寻找的所有成分的食谱。
答案 1 :(得分:0)
我对MySQL不太熟悉,但可以做类似的事吗?
SELECT r.*
FROM recipes AS r
LEFT JOIN recipe_sites AS s ON r.site_id = s.id
WHERE '%salt%' IN (SELECT i.name
FROM ingredients AS i
LEFT JOIN recipe_ingredients AS ri ON i.id = ri.ingredient_id
LEFT JOIN recipes AS r ON ri.recipe_id = r.id)
GROUP BY r.id;
这样做的正确方法是什么?