如何在子查询中使用INNER JOIN和UNION?

问题描述

我正试图找到在素食菜肴中都使用的配料。此练习要求我使用查询内部联接联盟

这是我目前拥有的:

SELECT Ingredients.Name
FROM
(
  SELECT Tags.Name
  FROM Tags
  INNER JOIN dishesTags ON dishesTags.TagID = Tags.ID
  INNER JOIN dishes ON dishesTags.dishID = dishes.ID
  INNER JOIN dishesIngredients ON dishesIngredients.dishID = dishes.ID
) Ingredients
WHERE Tags.Name IN ('Spicy','vegetarian')

但是,我不太了解如何在联合子查询上使用并集?

Here is the diagram of the database for reference

解决方法

一个选项使用聚合和having子句进行过滤:

select i.name
from ingredients i
inner join dishesingredients di on di.ingredientid = i.id
inner join dishestags dt on dt.dishid = di.dishid
inner join tags t on t.id = dt.tagid
where t.name in ('Spicy','Vegetarian')   -- either one tag or the other
group by i.id,i.name
having count(distinct t.name) = 2         -- both tags where found