gpt4 book ai didi

sql - 使用 MySQL 中另一个表的多个条件计算不同的记录

转载 作者:可可西里 更新时间:2023-11-01 07:24:00 26 4
gpt4 key购买 nike

这不是家庭作业。我更改了表和字段的名称,仅供说明之用。我承认我对 MySQL 完全陌生。请在您的回答中考虑这一点。

说明我需要的查询功能的最好方式是这样的:

我有两个表。

一个表与另一个表有 0..1 到 0..n 的关系。

为了简单起见,假设这两个表是 Recipe 和 Ingredient。

Ingredient 表中的一个字段引用 Recipe 表,但可能为空。

举个例子: alt text

我想知道类似以下内容的 SQL:有多少食谱需要“1”的“橄榄”和“2”的“蘑菇”

作为 The Structured Query Language 的新手,我什至不知道要用 google 搜索什么信息。

我是否走在正确的轨道上?:

SELECT COUNT(DISTINCT Recipe.ID) AS Answer FROM Recipe, Ingredient 
WHERE Ingredient.RecipeID=Recipe.ID AND Ingredient.Name='Olives'
AND Ingredient.Amount=1 AND Ingredient.Name='Mushrooms'
AND Ingredient.Amount=2

我意识到这是完全错误的,因为 Name 不能同时是 Olives 和 Mushrooms...但不知道该放什么,因为我需要计算所有包含两者的食谱,但只计算包含两者的所有食谱。

如何为 MySQL 正确编写这样的查询?

最佳答案

你很接近。

尝试类似的东西

SELECT  COUNT(Recipe.ID) Answer
FROM Recipe INNER JOIN
Ingredient olives ON olives.RecipeID=Recipe.ID INNER JOIN
Ingredient mushrooms ON mushrooms.RecipeID=Recipe.ID
WHERE olives.Name='Olives'
AND mushrooms.Name='Mushrooms'
AND olives.Amount = 1
AND mushrooms.Amount = 2

您可以两次连接到同一个表,您需要做的就是给表一个合适的 alias .

关于sql - 使用 MySQL 中另一个表的多个条件计算不同的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4222057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com