如何将查询与子查询连接起来?
Posted
技术标签:
【中文标题】如何将查询与子查询连接起来?【英文标题】:How to join queries with a subquery? 【发布时间】:2020-09-28 08:39:57 【问题描述】:所以我是一个完全新手,试图解决这个练习,我必须找到所有标记为素食但成分中含有火鸡肉的菜肴。
这是我尝试过的(这是我内部连接 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)
数据库的图在这里供参考:
【问题讨论】:
【参考方案1】:让我们先来看看有多少菜肴以火鸡肉为原料。
你有:
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'
然后获取所有带有“素食”标签的菜肴。
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'
【讨论】:
【参考方案2】:您可以使用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'
)
【讨论】:
以上是关于如何将查询与子查询连接起来?的主要内容,如果未能解决你的问题,请参考以下文章