SQL使用表中的多个值从另一表中的一个字段获取相应的值

时间:2018-10-09 14:26:50

标签: sql join left-join

我有两个表attr_tblfreq_tbl

attr_tbl字段:

attr_ky - numeric
attr_name - character

attr_tbl示例:

attr_ky | attr_name
   1    |  driver 
   2    |  athlete 
   3    |  parent 

freq_tbl字段:

att1 - numeric
att2 - numeric
att3 - numeric
freq - numeric

样本freq_tbl:

att1 | att2 | att3 | freq
  1  |   2  |  3   | 1000 

我基本上想在 freq_tbl 中再添加三列。
att1_name :与attr_name对应的att1
att2_name :与attr_name对应的att2
att3_name :与attr_name对应的att3

所需结果:

att1 | att2 | att3 | freq | att1_name | att2_name | att3_name
   1 |   2  |   3  | 1000 |  driver   |  athlete  |  parent

我知道如何使用多个sql语句来执行此操作,但是我想知道如何使用一个sql语句来执行此操作。预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试一下。

select 
    T.att1, 
    T.att2, 
    T.att3, 
    T.freq, 
    A1.attr_name AS att1_name, 
    A2.attr_name AS att2_name, 
    A3.attr_name AS att3_name
from freq_tbl T
    LEFT JOIN attr_tbl A1 ON T.att1 = A1.attr_ky
    LEFT JOIN attr_tbl A2 ON T.att2 = A2.attr_ky
    LEFT JOIN attr_tbl A3 ON T.att3 = A3.attr_ky