2016-02-10 267 views
0

此查詢應該選擇一些統計值形成一個表:的MySQL則返回0查詢爲空

(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') 
+0

什麼意思dosen't工作..錯誤。?錯誤的結果? .. – scaisEdge

+0

它返回一個錯誤,'#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'IFNULL((SELECT COUNT(*)'作爲\'count \'FROM \'stats \''WHERE DATE(\'time \')> = NOW() - 我在第2行' –

回答

0

你要做SELECTIFNULL

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',並得到擺脫圍繞第一個查詢的括號。

+0

這非常有幫助,非常感謝! –