作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在尝试创建一个实际上非常简单的 SQL 语句时,我发现自己迷失了方向。
我有一个包含 3 个表的数据库:
id | name 1 | lasagne alla bolognese 2 | tuna with tomatoes
ingredients:
id | name 1 | lasagne slices 2 | meat 3 | tomato 4 | tuna
and join-table ingredients_recipes:
ingredient_id | recipes_id 1 | 1 2 | 1 3 | 1 3 | 2 4 | 2
So as you can see, there are 2 really undelicios recipes which I should at least give some spices. But what I want to do before is selecting recipes by ingredients.
I want to have all my recipes having meat AND tomatoes:
SELECT recipes.name FROM recipes r
INNER JOIN ingredients_recipes ir ON ir.recipes_id = r.id
WHERE ir.ingredient_id IN ( 2 ) AND ir.ingredient_id IN ( 3 )
SELECT recipes.name FROM recipes r
INNER JOIN ingredients_recipes ir ON ir.recipes_id = r.id
WHERE ir.ingredient_id IN ( 2 ) AND ir.ingredient_id NOT IN ( 4 )
SELECT recipes.name FROM recipes r
INNER JOIN ingredients_recipes ir ON ir.recipes_id = r.id
WHERE (
ir.ingredient_id IN ( 2 ) -- or more..
AND
recipes.id NOT IN ( SELECT recipes_id FROM ingredients_recipes
WHERE ingredient_id IN ( 4 ) -- actually i paste names of the ingredients.. but that is not the case. just to shorten the query.. by filling in a comment twice as long..
)
)
IN(awesome).
最佳答案
这是一种方式。 (未经测试)
SELECT r.name
FROM recipes r
JOIN ingredients_recipes ir
ON ir.recipe_id = r.id
WHERE EXISTS ( SELECT *
FROM ingredients_recipes ex
WHERE ex.recipe_id = r.recipe_id
AND ex.ingredient_id IN ( 2 , 3 )
GROUP BY nx.recipe_id
HAVING COUNT(*) = 2
);
SELECT r.name
FROM recipes r
JOIN ingredients_recipes ir
ON ir.recipe_id = r.id
WHERE EXISTS ( SELECT *
FROM ingredients_recipes ex
WHERE ex.recipe_id = r.recipe_id
AND ex.ingredient_id = 2
)
AND EXISTS ( SELECT *
FROM ingredients_recipes ex
WHERE ex.recipe_id = r.recipe_id
AND ex.ingredient_id = 3
);
... AND NOT EXISTS ( SELECT *
FROM ingredients_recipes ex
WHERE ex.recipe_id = r.recipe_id
AND ex.ingredient_id IN ( 4,5 )
);
关于SQL NOT IN 解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11181472/
我是一名优秀的程序员,十分优秀!