如何在多个表之间分支查询

时间:2013-06-04 09:42:51

标签: sql database tsql informix

如果我有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 该怎么做(性能明智)。

2 个答案:

答案 0 :(得分:1)

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, '') <> ''

答案 1 :(得分:1)

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