如果某些条件为真,则返回不同的值

时间:2014-06-18 18:43:38

标签: sql sql-server-2008

我有这个问题:

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)

然后返回值A else返回值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'

2 个答案:

答案 0 :(得分:0)

您无法从where子句中的表中选择数据。你只是无法访问它们。但是,通过稍微更改您的查询,您可以按照自己的要求进行操作。不要在where子句中使用子选择,而是将其移动到查询的选择部分(WHAT ?!)。没错,您可以在选择中进行子选择。

由于你正在检查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'

所以发生了什么,如果cam.device_id在表中,你正在寻找lu_camera_ext中的新值。如果未使用子选择返回device_id,则返回null。然后isnull评估返回的值。如果你得到null,那么就像往常一样返回last_ddns_update_time。

答案 1 :(得分:0)

等同于If / Else的SQL是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'
相关问题