SQL:在join

时间:2015-10-28 08:51:52

标签: sql postgresql select join

我有3张桌子:

表:Info看起来像

id Name code_category_id code_confirmed_status_id
5  I001 266              49
10 I005 267              48

Survey看起来像

worker_id code_number_of_days_id code_gender
5           413                     7
10          412                     8

code看起来像

id type                value
413 number_of_days     4
412 number_of_days     5
266 category_id        25-32
267 category_id        30-35
 48 confirmed_status   Full-time
 49 confirmed_status   Part-time
  7 gender             Male
  8 gender             Female

我想加入这些表格,以便我拥有代码编号被代码值替换的所有信息。我的决赛桌

 worker_id code_number_of_days_id code_gender Name code_category_id code_confirmed_status_id
 5         4                      Male        I001                  Full-time   
 10        5                     Female       I005                  Part-time

我可以使用join

组合表格
select survey.worker_id,
       survey.code_number_of_days_id,
       survey.code_gender,
       Info.Name, 
       Info.code_category_id, 
       Info.code_confirmed_status_id
from Survey 
  full outer join Info 
    on Survey.worker_id = Info.id 

结果是我想要的表,但代码是一些数字,我想用代码表中的特定代码值替换它们。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您好我认为以下查询是您要找的内容

select survey.worker_id,
   (Select Value from Code where ID = survey.code_number_of_days_id) as No_of_Days,
   (Select Value from Code where ID = survey.code_gender) as Gender,
   Info.Name, 
   (Select Value from Code where ID = Info.code_category_id) as Category,
   (Select Value from Code where ID = Info.code_confirmed_status_id) as Confirmed,
from Survey 
full outer join Info 
on Survey.worker_id = Info.id