sql查询无结果设置默认值 | 您所在的位置:网站首页 › sql怎么设置默认值 › sql查询无结果设置默认值 |
笔记:
最近SQL直挂图表数据显示无内容,看了下数据库发现表里没数据,三方图表默认显示文字,但是需求想显示结果0。 所以要想办法把无结果得数据默认给一个默认值。 查询字段通常分为“”、null两种,前提是有结果,但是字段可能没数据,用case when 和ifnull都能解决。 但是如果查出来连数据都没有,空表。上面方法无效。 大量查帖,有left jion(也要有数据)。有使用union或者union all 拼一个默认数据得临时表,如下: SELECT time AS date, count FROM table1 WHERE time year(getDate()) union all SELECT now() AS date, 0 AS count FROM table1 where NOT EXISTS(SELECT 1 FROM table1 WHERE time year(getDate()))意思就如果这个表里没数据就union一个临时表给默认数据为date=当前事件,count=0 坑:发现如何设置默认值都无法显示 0 rows 思路对了,多试几次发现 SELECT time AS date, count FROM table1 WHERE time year(getDate()) union all SELECT now() AS date, 0 AS count where NOT EXISTS(SELECT 1 FROM table1 WHERE time year(getDate())) 这么写就对了,区别是union 后面得表 select now(),0; 直接跟where 没有from table1。 这里可能是理解不够深刻,也可能是版本问题吧。大部分文章中都是from 当前表的。自行探索 1 row |
CopyRight 2018-2019 实验室设备网 版权所有 |