如果查询为null,则MySQL返回0

时间:2016-02-10 18:11:39

标签: mysql

此查询应从表格中选择一些统计值:

(SELECT MAX(`id`) as `count` FROM `stats` LIMIT 1)
UNION (SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 1 DAY) LIMIT 1)
UNION (SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 7 DAY) LIMIT 1)
UNION (SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 30 DAY) LIMIT 1)
UNION (SELECT DATE_FORMAT(MIN(`time`), '%D of %M, %Y') as `count` FROM `stats` LIMIT 1)

我试过了,但它没有用

(SELECT MAX(`id`) as `count` FROM `stats` LIMIT 1)
UNION IFNULL((SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 1 DAY) LIMIT 1), '0')
UNION IFNULL((SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 7 DAY) LIMIT 1), '0')
UNION IFNULL((SELECT COUNT(*) as `count` FROM `stats` WHERE DATE(`time`) >= (NOW() - INTERVAL 30 DAY) LIMIT 1), '0')
UNION IFNULL((SELECT DATE_FORMAT(MIN(`time`), '%D of %M, %Y') as `count` FROM `stats` LIMIT 1), '0')

1 个答案:

答案 0 :(得分:0)

您必须SELECT上的IFNULL

SELECT MAX(`id`) as `count` FROM `stats` LIMIT 1
UNION 
SELECT IFNULL((SELECT COUNT(*) as `count` 
               FROM `stats` 
               WHERE DATE(`time`) >= (NOW() - INTERVAL 1 DAY) LIMIT 1), 0)
UNION 
SELECT IFNULL((SELECT COUNT(*) as `count` 
               FROM `stats` 
               WHERE DATE(`time`) >= (NOW() - INTERVAL 7 DAY) LIMIT 1), 0)
UNION 
SELECT IFNULL((SELECT COUNT(*) as `count` 
               FROM `stats` 
               WHERE DATE(`time`) >= (NOW() - INTERVAL 30 DAY) LIMIT 1), 0)
UNION 
SELECT IFNULL((SELECT DATE_FORMAT(MIN(`time`), '%D of %M, %Y') as `count` 
               FROM `stats` LIMIT 1), 0)

您还必须使用0代替' 0'并摆脱第一个查询周围的括号。