SYBASE:Join两个表,其中一个表列的值是其他表的列名

时间:2017-12-29 10:59:20

标签: sql join metadata sybase

  Table1 

PRICE   ID_1    ID_2    ID_3
 500    1       2       3
 750    2       3       4  


Table2

ID  VALUE  
ID_1    1  
ID_2    2  
ID_3    3  

我有两个表,想加入这些表,如

Select * from table1 T1 Join Table2 T2 on
T1.(T2.ID) = T2.Value

简而言之,我想在加入时将一个表列值转换为其他表列名。

EDITED 结果应该是这样的:

PRICE   ID_1    ID_2    ID_3  
 500    1       2       3

2 个答案:

答案 0 :(得分:0)

首先需要将行转换为第二个表中的列,然后加入两个表:

$len5
  C1 C2 C3 C4 C5
1  C  G  C  C  C

$len6
  C1 C2 C3 C4 C5 C6
1  C  C  T  G  C  T

$len7
  C1 C2 C3 C4 C5 C6 C7
1  G  G  C  G  A  C  T

$len8
  C1 C2 C3 C4 C5 C6 C7 C8
1  A  G  G  G  C  A  A  C

$len9
  C1 C2 C3 C4 C5 C6 C7 C8 C9
1  T  G  C  A  G  G  G  T  C

$len10
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10
1  C  T  C  T  T  G  C  T  C   A

$len11
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11
1  A  G  G  T  G  A  G  T  G   G   C

$len12
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12
1  A  G  A  C  G  C  C  C  A   C   C   T

$len13
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13
1  G  C  T  G  G  C  A  G  C   C   G   G   G

$len14
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14
1  G  A  C  A  C  T  G  C  A   G   G   G   C   C

$len15
  C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15
1  C  T  C  T  T  G  C  T  T   A   C   T   G   T   A

或者以其他方式执行,将表格转换为行:

Select * 
from table1 T1 
join
(

    SELECT
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_1,
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_2,
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_3
    from table

) as T2  on T1.ID_1 = T2.ID_1
        and T1.ID_2 = T2.ID_2
        and T1.ID_3 = T2.ID_3

答案 1 :(得分:0)

一种方法是:

Select *
from table1 T1 Join
     Table2 T2
     on t1.id_1 = T2.Value and t2.id = 'ID_1' or
        t1.id_2 = T2.Value and t2.id = 'ID_2' or
        t1.id_3 = T2.Value and t2.id = 'ID_3';

效率不高,但它应该完成你想要的逻辑。

编辑:

根据您的修改,您似乎想要:

select t1.*
from table1 t1
where exists (select 1 from table2 where t2.value = t1.id_1 and t2.id = 'ID_1') and
      exists (select 1 from table2 where t2.value = t1.id_2 and t2.id = 'ID_2') and
      exists (select 1 from table2 where t2.value = t1.id_3 and t2.id = 'ID_3') ;