如果我有 4 个这样的表:
1- mainemployees
emp_id
email
type (0-->ext,1-->internal,2--->special)
2-externalemp
emp_id
name
3-internalemp
emp_id
name
4-specialemp
emp_id
name
现在我想要employee names
第一个表的 emp_id = 最后三个表之一的 emp_id 如何做到这一点(性能方面)。
select nvl(ee.name, nvl(ie.name, se.name))
from mainemployees me
left join
externalemp ee
on ee.emp_id = me.emp_id
left join
internalemp ie
on ie.emp_id = me.emp_id
left join
specialem se
on se.emp_id = me.emp_id
where nvl(ee.name, '') <> ''
or nvl(ie.name, '') <> ''
or nvl(se.name, '') <> ''
create table mainemployees (emp_id int, emp_type int)
create table externalemp (emp_id int, name nvarchar(20))
create table internalemp (emp_id int, name nvarchar(20))
create table specialemp (emp_id int, name nvarchar(20))
insert into mainemployees (emp_id, emp_type) values (1, 0), (2, 1), (3, 2)
insert into externalemp (emp_id, name) values (1, 'external')
insert into internalemp (emp_id, name) values (2, 'internal')
insert into specialemp (emp_id, name) values (3, 'special')
对于查询,您使用 CASE 选择右列
SELECT
CASE me.emp_type WHEN 0 THEN ee.name WHEN 1 THEN ie.name WHEN 2 THEN se.name END
FROM mainemployees as me
LEFT JOIN externalemp as ee ON me.emp_id = ee.emp_id
LEFT JOIN internalemp as ie ON me.emp_id = ie.emp_id
LEFT JOIN specialemp as se ON me.emp_id = se.emp_id