MySQL:查询以获取使用所有给定成分的食谱
我有以下简化表:
CREATE TABLE recipe(id int, name varchar(25));
CREATE TABLE ingredient(name varchar(25));
CREATE TABLE uses_ingredient(recipe_id int, name varchar(25));
我想要进行一个查询,返回包含鸡肉和奶油的食谱的所有 id。
我尝试过,
SELECT recipe_id FROM uses_ingredient INNER JOIN
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream")
USING (name) GROUP BY recipe_id
HAVING COUNT(recipe_id) >= (SELECT COUNT(*) FROM theme);
这给了我:“错误1248(42000):每个派生表必须有自己的别名” 并且可能也是错误的。
接下来我尝试
SELECT recipe_id FROM
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream") AS t
INNER JOIN uses_ingredient USING (name)
GROUP BY recipe_id HAVING
COUNT(recipe_id)>= (SELECT COUNT(*) FROM t);
给出“错误1146(42S02):表'recipedb.t'不存在”
我想避免创建临时表,包括使用ENGINE = MEMORY。
I have the following simplified tables:
CREATE TABLE recipe(id int, name varchar(25));
CREATE TABLE ingredient(name varchar(25));
CREATE TABLE uses_ingredient(recipe_id int, name varchar(25));
I want to make a query that returns all id's of recipes that contain both Chicken and Cream.
I have tried
SELECT recipe_id FROM uses_ingredient INNER JOIN
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream")
USING (name) GROUP BY recipe_id
HAVING COUNT(recipe_id) >= (SELECT COUNT(*) FROM theme);
which gives me :"ERROR 1248 (42000): Every derived table must have its own alias"
and is probably wrong too.
Next I tried
SELECT recipe_id FROM
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream") AS t
INNER JOIN uses_ingredient USING (name)
GROUP BY recipe_id HAVING
COUNT(recipe_id)>= (SELECT COUNT(*) FROM t);
which gives "ERROR 1146 (42S02): Table 'recipedb.t' doesn't exist"
I want to avoid creating temporary tables including using ENGINE=MEMORY.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能有更好的思考方式,但我认为答案是两组的交集:那些含有鸡肉的食谱和那些含有奶油的食谱。如果您简化的不仅仅是列数,这可能对您不起作用。但我尝试了一些记录,看起来不错。
There is likely a better way to think of it, but I see the answer as the intersection of two sets: those recipes that have chicken in them and those recipes that have cream in them. This might not work for you if you simplified more than just the number of columns. But I tried it with a handful of records and it seems fine.
我同意 MJB 的观点;它是两个集合的交集。所以我就买了两套,看看里面都有什么......
I agree with MJB; it is the intersection of two sets. So I'd just get the two sets and see what's in both of them...
其他建议都很好,但这里有另一种方法。这实际上看起来像是您在查询中尝试执行的操作。虽然我不知道为什么当“uses_ingredient”中似乎包含相同的信息(名称)时,您会有“成分”表。
The other suggestions are good, but here is another way. This actually seems like what you were trying to do in your query. Although I don't know why you have and "ingredient" table when the same information (name) seems to be contained in "uses_ingredient".