首页 > 解决方案 > 如何将查询与子查询连接起来?

问题描述

所以我是一个完全新手,试图解决这个练习,我必须找到所有标记为素食但成分中含有火鸡的菜肴。

这是我尝试过的(这是我内部加入 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)

数据库图在这里供参考:

数据库的图在这里供参考

标签: sqlsql-serverjoinsubquery

解决方案


您可以使用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'
    )

推荐阅读