2014-06-18 66 views
0

我有這樣的查詢:返回不同的值,如果某些條件爲真

select last_ddns_update_time 
from lu_camera cam 
where cam.unit_id='90016980' 
     and cam.device_id='2051' 
     and cam.device_id not in (
        select device_id 
        from lu_camera_ext 
        where unit_id=cam.unit_id 
          and device_id=cam.device_id) 

它目前僅返回一個變量(從單元)。是否有可能返回兩個變量(一個來自單元格,另一個來自查詢本身)?

我希望它這樣,如果這部分是真實的:

(select device_id 
from lu_camera_ext 
where unit_id=cam.unit_id 
     and device_id=cam.device_id) 

然後返回值的其他人返回值B(select last_ddns_update_time, new_value)。我相對較新的SQL,所以我很抱歉,如果這是一個超級磨合問題。

東西有點像:

select last_ddns_update_time, new_value from lu_camera cam where cam.unit_id='90016980' and cam.device_id='2051' and cam.device_id 
and if (select device_id from lu_camera_ext where unit_id=cam.unit_id and device_id=cam.device_id) set new_value='a' 
else set new_value='b' 

回答

0

你不能在你選擇的是你的where子句中的表中獲取數據。你只是無法訪問它們。但是,通過改變你的查詢,你可以做你正在問的問題。而不是在where子句中有子選擇,讓我們將它移到查詢的選擇部分(什麼?!)。沒錯,你可以選擇一個子選擇。

由於您正在檢查cam.device_id是否在您的子選擇中,我將假設您想要'new_value',如果id在select中,否則您需要last_ddns_update_time。它看起來像這樣:

Select isnull((select new_value 
       from lu_camera_ext 
       where unit_id=cam.unit_id 
       and device_id=cam.device_id 
       and cam.device_id = device_id) 
     , last_ddns_update_time) 
from lu_camera cam 
where cam.unit_id='90016980' 
     and cam.device_id='2051' 

那麼究竟是什麼發生的事情是,你正在尋找從lu_camera_ext新的值,如果cam.device_id是在表中。如果device_id沒有與您的子選擇一起返回,則會返回null。然後isnull評估返回的值。如果返回null,則會按照慣例返回last_ddns_update_time。

0

SQL等同於If/Else是CASE關鍵字。此外,如果您使用「外連接」,查詢將更容易。試試這個:

select last_ddns_update_time, 
    CASE WHEN ext.device_id IS NULL THEN 'b' ELSE 'a' END as new_value 
from lu_camera cam LEFT JOIN lu_camera_ext ext ON cam.unit_id=ext.unit_id 
    and cam.device_id=ext.device_id 
where cam.unit_id='90016980' 
    and cam.device_id='2051' 
相關問題