2012-11-28 52 views
-1

我有两个表连接与左外连接Oracle查询设计

员工

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 

这是常见的查询我要取回所有员工基于location.here 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' 
+6

请不要使用隐式的连接在where子句。改用明确的'LEFT JOIN'。 –

+3

@a_horse_with_no_name - 请不要关于ANSI加入。它们很酷,但会导致Oracle优化器出现问题。 – APC

+0

你能澄清你的问题吗?你是否想返回等于'profile_location'的记录,但是如果该值不存在则返回记录? – Taryn

回答

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) 
+0

在这种情况下,它会返回重复的权利? – user1861226

+0

即使这个查询没有返回任何东西,因为没有值存在与空 – user1861226

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 with Demo

如果你在一个值传递不存在像'xxx'结果是:

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

如果您在'NYC'传递的结果是:

| EMPLOYEE_NAME | 
----------------- 
|   David | 
+0

谢谢,它不能解决我的问题,它应该返回记录那些通过条件e.location_id = ep.location_id,如果profile_location不存在 – user1861226

+0

@用户我认为你的意思,如果profile_location是NULL(不存在),你只需要匹配条件'e.location_id = ep.location_id',是否正确? – RichardTheKiwi

+0

@richard:是的,这是正确的 – user1861226