-1

我有两个表加入左外连接

员工

Employeed_Id    Employee_Name   Location_id

1               David           1
2               Andrew          2
3               Mike            3
4               steve           4

Employee_profile

profile_id     profile_name   location_id  profile_location
1              manager           1          NYC
2              accountant        2          Jersey
3              engineer          1          Mexico
4              trainer           3           Boston

这是我必须根据位置检索所有员工的常见查询。这里 profile_location 是唯一的。

问题是,在应用程序的某些部分 profile_location 不是必需的。因此,不需要上述表之间的外连接。

如何开发查询,以便在 profile_location 没有外连接输入值的情况下正常运行。

以下是我的查询:

select e.Employee_Name 
from Employee e,
     Employee_profile ep 
 where e.location_id (+) = ep.location_id
 and ep.profile_location='xxxxx'
4

2 回答 2

3

如果你想返回那些匹配你传入的记录,profile_location但又想在位置不存在时返回所有记录,那么你可以使用这样的东西:

select distinct e."Employee_Name"
from Employee e
left join Employee_profile ep 
  on e."Location_id" = ep."location_id"
where ep."profile_location" = 'xxx'
    or not exists (select ep1."profile_location" 
                   from Employee_profile ep1
                   where  ep1."profile_location" = 'xxx')

请参阅带有演示的 SQL Fiddle

如果您传入一个不存在的值,'xxx'结果如下:

| EMPLOYEE_NAME |
-----------------
|         David |
|        Andrew |
|         steve |
|          Mike |

如果你传入'NYC'结果是:

| EMPLOYEE_NAME |
-----------------
|         David |
于 2012-11-29T20:35:52.810 回答
0
select e.Employee_Name 
from Employee e,
     Employee_profile ep 
 where e.location_id (+) = ep.location_id
 and (ep.profile_location='xxxxx'
   Or ep.profile_location is null)
于 2012-11-28T21:54:26.503 回答