【问题标题】:Join Multiple tables based on value in one table根据一个表中的值连接多个表
【发布时间】:2020-11-29 09:20:35
【问题描述】:

我有 3 个表,我想根据 Table_A 中的条件加入 Table_A,如下所示:

  • Table_ADATA_1列中的值为“aaa”时,我想将它与Table1中的数据连接起来,如果是“bbb”,我想将其与表 2 中的数据连接起来。
Table_A     
ID  DATA_1  DATA2
------------------
1x  aaa      qwe
2q  bbb      axz
3w  ccc      qws
4b  aaa      dal
5a  ddd      qws

Table_1     
ID  DATA_1  DATA_2  DATA_Y
--------------------------
1x  aaa      qwe     wer

Table_2     
ID  DATA_1  DATA_X   DATA_Y
---------------------------
1x  bbb      qwe     wez

and so on..

到目前为止我所拥有的:

SELECT h.id,
       h.data_1,
       h.data_2,
       a.data_x,
       a.data_y
FROM   table_a h,
       table_1 a
WHERE  h.order_id = a.order_id
UNION
SELECT h.id,
       h.data_1,
       h.data_2,
       b.data_x,
       b.data_y
FROM   table_a h,
       table_2 b
WHERE  h.order_id = b.order_id 

有没有一种方法可以将所有内容组合到一个查询中,而不是进行联合?

【问题讨论】:

  • "combine" 没有特别的含义。这篇文章没有明确说明您希望查询做什么。 PS minimal reproducible example PS 有条件地加入不同的表是一个常见问题。 (我们不这样做,我们连接表格以获取每个可能的行组合,使用 on 和/或保留我们想要的行的位置,然后选择这些行的所需功能。) PS 请通过编辑澄清,而不是厘米。

标签: oracle join oracle-sqldeveloper union


【解决方案1】:

大概是这样的吧?加入 + CASE。参见第 17 行。

SQL> with
  2  -- sample data
  3  table_a (id, datat, data2) as
  4    (select '1x', 'aaa', 'qwe' from dual union all
  5     select '2q', 'bbb', 'axz' from dual union all
  6     select '3w', 'ccc', 'qws' from dual
  7    ),
  8  table_1 (id, datat, datax, datay) as
  9    (select '1x', 'aaa', 'tab1 qwe', 'wer' from dual union all
 10     select '2q', 'bbb', 'tab1 xxx', 'bab' from dual
 11    ),
 12  table_2 (id, datat, datax, datay) as
 13    (select '1x', 'aaa', 'tab2 qwe', 'wez' from dual union all
 14     select '2q', 'bbb', 'tab2 yyy', 'fdf' from dual
 15    )
 16  -- query which might help
 17  select h.id, h.datat, h.data2,
 18    case when h.datat = 'aaa' then a.datax
 19         when h.datat = 'bbb' then b.datax
 20    end datax,
 21    --
 22    case when h.datat = 'aaa' then a.datay
 23         when h.datat = 'bbb' then b.datay
 24    end datay
 25  from table_a h  join table_1 a on a.id = h.id
 26                  join table_2 b on b.id = h.id;

ID DAT DAT DATAX    DAT
-- --- --- -------- ---
1x aaa qwe tab1 qwe wer
2q bbb axz tab2 yyy fdf

SQL>

【讨论】:

  • @Littlefoot..感谢您的回复,但是当我尝试此操作时得到一个空输出
  • 嗯......我不(显然)。
  • 当我只保留 1 个 case 语句和一个表连接时,它可以工作..但是当我开始添加额外的 case /table 连接时,它不会显示任何内容。
  • 可能没有匹配项。您发布的示例数据比较通用,很难猜测真实情况。尝试切换到 outer join 看看会发生什么。
  • 奇怪,我试过了。左连接和外连接,但我得到空值。我将继续进行以下操作:select h*, coalesce (a.status,b.status) as stat from Table_A h left join Table_1 a on h.id = a.id left join Table_2 b on h.id = b.id
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多