行值是第2个表的列名,需要从第2个表中得到结果

时间:2017-05-31 09:24:04

标签: mysql

我需要从2个表中创建一个视图

表1

  app_id    cat_id  approver    level   proj_id

  1            1    pm_id         1       731
  1            2    dm_id         2       843
  1            3    dm_id         1       859
  2            4    bo_id         1       859

表2

  proj_id   pm_id   dm_id   bo_id

  731       100102  100034  100121
  843       123121  145721  104321
  859       112312  132434  132435

我的审批人ID在表2中,表1表示谁是基于级别的项目审批人。我想用pm,dm和bo。

为待批准列表创建一个视图

e.g。结果表

app_id  cat_id  approver

1         1      100102
1         2      145721
1         3      132434
2         4      132435

1 个答案:

答案 0 :(得分:0)

使用left join将两个表连接在一起,然后使用case when获取批准者。

select
    table1.app_id,
    table1.cat_id,
    case when table1.approver = 'pm_id' then table2.pm_id
         when table1.approver = 'dm_id' then table2.dm_id
         when table1.approver = 'bo_id' then table2.bo_id
    end as approver
from table1
left join table2 on table1.proj_id = table2.proj_id

请参阅rextester中的demo

<强> 修改

如果您有动态审批者,请尝试以下操作:

SET @sql = NULL;
SELECT
  CONCAT('CASE', GROUP_CONCAT(DISTINCT
      CONCAT(' WHEN table1.approver = ''',
      approver,
      ''' THEN table2.', approver) SEPARATOR ' '), ' END AS approver'
  ) INTO @sql
FROM table1;


SET @sql = CONCAT('SELECT table1.app_id, table1.cat_id, ', @sql, ' FROM table1 LEFT JOIN table2 ON table1.proj_id = table2.proj_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

在Rextester中也有demo

创建 VIEW

create view view1
as
select
    table1.app_id,
    table1.cat_id,
    case when table1.approver = 'pm_id' then table2.pm_id
         when table1.approver = 'dm_id' then table2.dm_id
         when table1.approver = 'bo_id' then table2.bo_id
    end as approver
from table1
left join table2 on table1.proj_id = table2.proj_id