【问题标题】:How to use INNER JOIN and UNION with a subquery?如何在子查询中使用 INNER JOIN 和 UNION?
【发布时间】:2021-01-14 07:38:29
【问题描述】:

我正在尝试寻找用于素食 菜肴的配料。这个练习需要我使用子查询inner joinunion

这是我目前拥有的:

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')

但是,我不太明白如何在连接的子查询上使用联合?

【问题讨论】:

  • 你为什么使用UNIONEXISTS 不是更好的解决方案。 UNION 从您的描述来看,一开始似乎是错误的选择。示例数据和预期结果可能会对我们有所帮助。
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你的期望和原因。
  • 您的问题是什么? “用”是为了什么? PS t where c or d is t where c union t where d.我们可以期待这是一个常见问题解答。请在考虑发布之前阅读您的教科书和/或手册和谷歌任何错误消息或您的问题/问题/目标的许多清晰、简洁和精确的措辞,有和没有您的特定字符串/名称和站点:stackoverflow.com 和标签;阅读许多答案。请use text, not images/links, for text--including tables & ERDs。仅将图像用于无法表达为文本或增强文本的内容。包括一个图例/键。

标签: sql sql-server subquery inner-join union


【解决方案1】:

一个选项使用聚合和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

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多