【问题标题】:Conditional join from different tables来自不同表的条件连接
【发布时间】:2016-01-11 05:34:17
【问题描述】:

我有一张桌子,看起来像 Items:

id   index
1     45
1     50
2     25
2     45

我正在写一个查询 从items 中选择所有行。我需要用它的描述替换索引。 id 1表示table_a,id 2表示table_b。

表_A

index   description
45          'ddd'
50          'fff'

表_B

index   description
25          'AAA'
45          'BBB'

意思是我需要加入索引,但取决于 id。

类似:

Select id,index,description
from items
join table_A,table_B using (index)

我想得到的是:

id index description

1    45    'ddd'
1    50    'fff'
2    25    'AAA'
2    45    'BBB'

如何使用 1 个加入来做到这一点?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你必须先 UNION Table_A & Table_B,然后加入 Items 如下

    Select id,index,T.description from items
    join (select 1 as id, index, description from Table_A 
    UNION select 2 as id, index, description from Table_B) as T
    ON items.id=T.id and items.index=T.index
    

    【讨论】:

      【解决方案2】:

      假设 UNION 不算作一个连接,那么:

      SELECT i.id, i.index, u.description
        FROM Items AS i
        JOIN (SELECT 1 AS id, index, description FROM Table_A
              UNION
              SELECT 2 AS id, index, description FROM Table_B
             ) AS u
          ON u.id = i.id AND i.index = u.index;
      

      【讨论】:

        【解决方案3】:

        您可以在不使用单个连接语句的情况下做到这一点。

        select a.id_,a.indx, decode(a.id_,1,(select description from table_a where indx=a.indx), 2,(select description from table_b where indx=a.indx)) description from item a

        它将提供所需的输出。但我认为indx=a.indx 将充当反连接(隐式连接类型)。

        在 decode 中的每次迭代中只执行一个 select 语句。 所以一次只能加入一个。

        如果我错了,请告诉我。

        【讨论】:

          猜你喜欢
          • 2021-09-04
          • 1970-01-01
          • 1970-01-01
          • 2017-11-14
          • 2014-12-30
          • 1970-01-01
          • 2012-02-03
          • 2011-06-21
          • 2013-09-24
          相关资源
          最近更新 更多