如何在SQL中的左外连接中实现“任一 - 或”方案

时间:2011-09-22 18:58:41

标签: sql

我是SQL查询的新手,我正在努力解决以下问题。

我必须实现这样的事情:

Select person.name, person.age, employee.yearsofservice

from person

join employee on person.name = employee.name

join fulltimeemployed on person.name = fulltimeemployed.name

join parttimeemployed on person.name = parttimeemployed.name

where fulltimeemployed.manager = 'Rob'  or parttimeemployed.manager = 'Rob'

基本上我想提取一份所有全职和兼职员工的名单,他们的经理是'Rob'。

但是上面的查询给出了空结果,因为员工不能同时出现在fulltimemployed和兼职工作表中。

所以我需要一种在这两个连接(fulltimeemployed和parttimeemployed)之间实现OR子句的方法。请提出任何想法:(

4 个答案:

答案 0 :(得分:2)

select person.name, person.age, employee.yearsofservice
from person
join employee on person.name = employee.name
join (
  select name from fulltimeemployed where manager = 'Rob'
  union all select name from parttimeemployed where manager = 'Rob') employed
on person.name = employed.name

答案 1 :(得分:0)

你应该为此做左外连接:

Select person.name, person.age, employee.yearsofservice
from person
join employee on person.name = employee.name
left outer join fulltimeemployed on person.name = fulltimeemployed.name
left outer join parttimeemployed on person.name = parttimeemployed.name
where fulltimeemployed.manager = 'Rob'  or parttimeemployed.manager = 'Rob'

答案 2 :(得分:0)

我怀疑是否需要有一张员工表,然后是两张不同的表来表示完整与兼职以及加入名字的智慧,但这也有效(注意我加入全员工作和兼职工作给员工而不是员工):

Select
    p.name
    ,p.age
    ,e.yearsofservice
from person AS p
join employee AS e on p.name = e.name
left outer join fulltimeemployed AS ft on p.name = ft.name
    AND ft.Manager = 'Rob'
left outer join parttimeemployed AS pt on p.name = pt.name
    AND pt.manager = 'Rob'

答案 3 :(得分:0)

Select person.name, person.age, employee.yearsofservice
from person
join employee on person.name = employee.name

left join fulltimeemployed on person.name = fulltimeemployed.name
and  fulltimeemployed.manager = 'Rob'
left join parttimeemployed on person.name = parttimeemployed.name
and parttimeemployed.manager = 'Rob'

where fulltimeemployed.id is not null
or fulltimeemployed.id is not null