【问题标题】:Loop through multiple tables to find match from table1 value [closed]循环遍历多个表以从 table1 值中查找匹配项 [关闭]
【发布时间】:2020-10-13 19:00:59
【问题描述】:

我有 4 到 5 个表都可以与 表 1(ID) 相关 根据表 1“ID”列中的值,我想遍历表 2、3 和 4 以找到匹配项。找到匹配项后,我想从该表中提取另一列。有什么帮助吗?

预期输出(一旦在表 2 或表 3 中找到匹配项)

【问题讨论】:

  • 您的问题只有两张表,而您提到了四个,这使事情变得不清楚。您还需要展示您期望的结果。
  • @GMB - 表 2、3、4 与表 2 类似
  • @a_horse_with_no_name - 我正在使用 sql developer
  • use text, not images/links, for text--including tables & ERDs。仅将图像用于无法表达为文本或增强文本的内容。请在代码问题中给出minimal reproducible example--cut & paste & runnable code 等。展示你能做的部分。 How to Ask 通过编辑而不是 cmets 进行澄清。 PS 为什么说 SQL 中的“循环”?
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 暂停整体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。

标签: sql oracle join select


【解决方案1】:

你可以使用exists:

select t1.*
from table1 t1
where 
    exists (select 1 from table2 t2 where t2.id = t1.id)
    or exists (select 1 from table3 t3 where t3.id = t1.id)

如果您想显示来自其他表的数据,请改用left joins:

select t1.id, t2.col1, t3.cola
from table1 t1
left join table2 t2 on t2.id = t1.id
left join table3 t3 on t3.id = t1.id
where coalesce(t2.id, t3.id) is not null

【讨论】:

  • 我重新表述了我的问题,几乎没有图片表示。我希望我的问题现在更清楚了吗?很抱歉之前的混乱
  • @ThomasKennedy:查看我的更新答案。
  • 我稍微更新了要求,并展示了我尝试过但不希望重复的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 2020-06-19
  • 2021-02-02
  • 1970-01-01
  • 2017-03-24
  • 2014-09-23
相关资源
最近更新 更多