查询以根据另一个表的值获取列值,即一个表值在另一个表中具有字段名称

时间:2014-10-31 09:48:24

标签: mysql sql

我有两个表hrm_m_allowance,pay_m_allowance。

hrm_m_allowance包含......

等字段
INT_APPID       INT_BASIC  A0001 A0002 A0003 A0004 A0005
---------------------------------------------------------
14              7900       1200  700   2000  1000   500

pay_m_allowance包含...............

等字段
CHR_ACODE  CHR_ANAME  CHR_BONUS .......etc
----------------------------------------------
A0001       HRA        0
A0002       DA         0
A0003       PF         0
A0004       ESI        0

现在我必须得到像

这样的值
BASIC    7900
HRA      1200     
DA        700
PF       2000
ESI      1000

请帮助我如何使用mysql查询获取上述值

1 个答案:

答案 0 :(得分:0)

时髦的数据库设计。我建议先删除数据,然后再执行join

select coalesce(pb.chr_aname, col) as chr_aname, h.val
from (select 'INT_BASIC' as col, INT_BASIC as val from hrm_m_allowance union all
      select 'A0001' as col, A0001 as val from hrm_m_allowance union all
      select 'A0002' as col, A0002 as val from hrm_m_allowance union all
      select 'A0003' as col, A0003 as val from hrm_m_allowance union all
      select 'A0004' as col, A0004 as val from hrm_m_allowance union all
      select 'A0005' as col, A0005 as val from hrm_m_allowance
     ) h left join
     pay_m_allowance pb
     on pb.chr_acode = h.col;

使用此方法的一个警告:当所有列具有相同的数据类型时,它将最有效。