如何将查询与子查询连接起来?

How to join queries with a subquery?

所以我是一个新手,试图解决这个问题,我必须找到所有标记为 Vegetarian 但包含 Turkey meat[的菜肴] =25=] 在他们的成分中。

这是我尝试过的方法(这是我内部连接 ​​3 个表以查找成分的地方):

SELECT Name
FROM Dishes
INNER JOIN DishesIngredients ON DishesIngredients.DishId = s.Id
INNER JOIN Ingredients ON DishesIngredients.IngredientID = Ingredients.ID

这是我似乎无法加入子查询以识别 Vegetarian 标签的地方:

WHERE Ingredients.Name = 'Turkey meat' =
(SELECT Name
FROM Tags
INNER JOIN DishesTags ON DishesTags.TagID = Tags.ID
INNER JOIN Dishes ON DishesTags.DishID = Dishes.ID)

数据库图在此供参考:

您可以使用 exists 和子查询:

select d.*
from dishes d
where
    exists (
        select 1 
        from dishestags dt
        innerjoin tags t on t.id = dt.tagid
        where dt.dishid = d.id and t.name = 'Vegetarian'
    )
    and exists (
        select 1 
        from dishesingredients di
        inner join ingredients i on i.id = di.ingredientid
        where di.dishid = d.id and i.name = 'Turkey'
    )

先看看有多少道菜的原料是火鸡肉

你有:

SELECT D.ID
FROM
Dishes D 
JOIN DishIngredients DI ON D.ID = DI.DishID
JOIN Ingredients I ON DI.IngredientID = I.ID
WHERE I.Name LIKE 'Turkey meat'

然后获取标签为'Vegetarian'的所有菜肴。

SELECT D.ID
FROM
Dishes D 
JOIN DishIngredients DI ON D.ID = DI.DishID
JOIN Ingredients I ON DI.IngredientID = I.ID
JOIN DishesTags DT on D.ID = DT.DishID
JOIN Tags T ON DT.TagID = T.ID

WHERE I.Name LIKE 'Turkey meat'
AND T.Name = 'Vegetarian'