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

Sql 如果某些条件为真,则返回不同的值,sql,sql-server-2008,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

我有一个疑问:

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,否则返回值B(
选择上次更新时间,新值
)。我对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'

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

由于您正在检查cam.device\u id是否在您的子选择中,因此我假设如果id在选择中,您需要“new\u值”,否则您需要最后的更新时间。看起来是这样的:

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\u id在表中,您正在从lu\u camera\u ext查找新值。如果设备id未随子选择一起返回,则将返回null。然后isnull计算返回值。如果返回空值,则将按常规返回上次更新时间。

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'