如果查询没有数据,请获取默认值?

时间:2015-07-01 09:26:59

标签: mysql database stored-procedures

我有一个存储过程,我在一段时间间隔内查询数据。所以我写了下面的查询要在存储过程中执行:

SET @quer = CONCAT('INSERT INTO tmp (`time_interval`, `cnt`, `dat`, `txn_id`) (SELECT DATE_FORMAT(\'', tmpStart, '\', \'%H:%i\') as time_interval , COUNT(v.id) as cnt
     , date(v.timestamp) as dat, \"', _txn_id, '\" as txn_id FROM vehicle v WHERE v.timestamp BETWEEN \'', tmpStart, '\'
                        AND \'', tmpEnd, '\' ', _where_clause, ' GROUP BY time_interval)')

但问题是,我希望它在没有值的时间间隔插入0。

Actual : for 01:00 - 02:00 = 12
         for 03:00 - 04:00 = 10
Expected:for 01:00 - 02:00 = 12
         for 02:00 - 03:00 = 0
         for 03:00 - 04:00 = 10

请有人建议我如何更改查询以获得此结果。

感谢。

3 个答案:

答案 0 :(得分:0)

尝试使用coalesce函数,如果column为null,则coalesce函数将您的值设为默认值,例如:

SELECT id, ..., coalesce(columnWithNulls, DefaultValue) FROM ...

答案 1 :(得分:0)

尝试使用IFNULL功能

Gender: <div class="genderCont">Male <input type="radio" id="gender" /> </div> <input type="submit" class="genderSubmitBtn" value="Submit" id="submit" />

答案 2 :(得分:0)

我使用此查询得到了答案。使用默认值0联合ALL。

SET @quer = CONCAT('INSERT INTO tmp (`time_interval`, `cnt`, `dat`, `txn_id`) Select * FROM (SELECT DATE_FORMAT(\'', tmpStart, '\', \'%H:%i\') as time_interval , COUNT(v.id) as cnt
 , date(v.timestamp) as dat, \"', _txn_id, '\" as txn_id FROM vehicle v WHERE v.timestamp BETWEEN \'', tmpStart, '\'
                    AND \'', tmpEnd, '\' ', _where_clause, ' GROUP BY time_interval UNION ALL SELECT DATE_FORMAT(\'', tmpStart, '\', \'%H:%i\') as time_interval , 0 as cnt
 , date(\'', tmpStart, '\') as dat, \"', _txn_id, '\" as txn_id) AS A GROUP BY A.time_interval');