一个表中的许多列加入一个引用表

时间:2018-10-18 04:32:39

标签: sql inner-join dbforge

image。所以很新,请客气。使用DBForge查询生成器

我有一个表,表中有许多包含缩写的列。 另一个表包含缩写的描述。

需要编写查询以将所有缩写替换为其描述。尝试了许多联接,但均未成功。有什么想法吗?

T1

ID  Date    Type    Cat Sub Cat
1   01/09/18    E   F   L
2   05/09/18    Cc  F   D
3   06/09/18    Cc  C   Dr
4   08/09/18    Cc  C   Sh
5   08/09/18    E   C   Sh

T2

Code    Des
E   Eft Payment
Cc  Credit Card
F   Food
C   Clothes
B   Breakfast
L   Lunch
D   Dinner
Sh  Shirt
Dr  Dress

所需的输出

ID  Date    Type D  Cat D   Sub Cat D
1   01/09/18    Eft Payment Food    Lunch
2   05/09/18    Credit Card Food    Dinner
3   06/09/18    Credit Card Clothes Dress
4   08/09/18    Credit Card Clothes Shirt
5   08/09/18    Eft Payment Clothes Shirt

3 个答案:

答案 0 :(得分:0)

在下面尝试使用T2使用不同别名的多个联接

select 
   a.ID, a.date,
   b.Des as TypeD, 
   c.Des as CatD,
   d.Des as SubCatD
from T1 a inner join T2 b on a.type=b.code
inner join T2 c on a.Cat=c.code
inner join T2 d in a.SubCat=d.code

答案 1 :(得分:0)

您需要使用T2表的多个实例:

select t1.id, t1.date, typ.des as type_d,ca.des as cat_d,subca.des as sub_cat_d from T1 t1 
inner join T2 typ on t1.type=typ.code 
inner join T2 ca on t1.cat = ca.code 
inner join T2 subca  on t1.subcat = subca.code;

尝试一下...

答案 2 :(得分:0)

我将假设T1的列为(ID, Date, Type, Cat, SubCat

SELECT T1.ID, T1.Date, T2Type.Des, T2Cat.Des, T2SubCat.Des
FROM T1 INNER JOIN T2 T2Type   ON T1.Type   = T2Type.Code
        INNER JOIN T2 T2Cat    ON T1.Cat    = T2Cat.Code
        INNER JOIN T2 T2SubCat ON T1.SubCat = T2SubCat.Code