如何在mysql中为子查询赋予默认值?

时间:2014-06-12 08:42:57

标签: mysql sql

在我的查询中,我可以为子查询提供一些默认值吗?

我的一个子查询可能没有任何值..在这种情况下,它返回null作为整个结果。如果甚至一个子查询为空,我可以指定一些默认值吗?

select 
    t1 . *, t2.speed, t3.Accelerometerx
from
    (SELECT 
        *
    FROM
        `table1`
    ) as t1,
    (SELECT 
       *
    FROM
        table1)
    as t2

3 个答案:

答案 0 :(得分:0)

检查nvl函数,它应该可以解决你的问题。

答案 1 :(得分:0)

使用案例/如:

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

示例,而不是:

where
    `vehicle_tripdetails`.`Param_ID` = '131'
        and trip_id = 127) as t1,
(SELECT 
    time_stamp, `vehicle_tripdetails`.`Param_Data` as speed
FROM
    `vehicle_tripdetails`
where
    `vehicle_tripdetails`.`Param_ID` = '13'
        and trip_id = 127) as t2,

您可以使用:

where
    `vehicle_tripdetails`.`Param_ID` = '131'
        and trip_id = 127) as t1,
CASE 
  WHEN (SELECT  time_stamp, `vehicle_tripdetails`.`Param_Data` as speed FROM
    `vehicle_tripdetails` where
    `vehicle_tripdetails`.`Param_ID` = '13'
        and trip_id = 127) 
  IS NOT NULL 
THEN (SELECT  time_stamp, `vehicle_tripdetails`.`Param_Data` as speed FROM
    `vehicle_tripdetails` where
    `vehicle_tripdetails`.`Param_ID` = '13'
        and trip_id = 127) 
ELSE
   'default value'
END CASE
AS t2

答案 2 :(得分:0)

在您的select子句中使用ISNull,如下所示

select    t1.*,
          CASE ISNULL(t2.speed) WHEN 1 THEN 0 ELSE t2.speed END,
          CASE ISNULL(t3.xyz) WHEN 1 THEN 0 ELSE t3.xyz END

此处默认值为0.如果您不使用*

选择所有记录,这将有效