使用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。
编辑:
如果具有动态的审批,试试这个:
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
内连接http://www.mysqltutorial.org/mysql-inner-join.aspx –
'选择table1.app_id,table1.cat_id,table2.pm_id作为table1内部连接table2的批准者,在table1.proj_id = table2.proj_id'现在尝试通过自己学习更多,在线阅读一些tutorail做一些研究。 –
这里是一些堆栈溢出文档https://stackoverflow.com/documentation/mysql/2736/joins#t=201705310934419709604 –