使用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 –