2012-11-28 54 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