如果没有结果,MySQL查询返回数字'零'

时间:2012-02-28 18:55:22

标签: mysql sum resultset zero

选择DATE并且我的表中不存在该日期时,它当前将返回空结果集。我怎样才能为这些空结果集返回零号?:

    SELECT SUM(TOTAL), SUM(5STAR), STORE, DATE
    FROM `table` WHERE DATE >= '2012-02-24' GROUP BY TOTAL

MySQL returned an empty result set (i.e. zero rows)

我希望将SUM(TOTAL)SUM(5STAR)(如果为零行)的结果返回为数字零(0)。

全表结构:

  • ID =主要
  • DATE = UNIQUE(date)
  • STORE
  • 五星
  • 4星
  • 星级的
  • 2星级的
  • 1STAR
  • TOTAL
  • FROM = UNIQUE

3 个答案:

答案 0 :(得分:18)

尝试COALESCE

SELECT COALESCE(SUM(TOTAL),0), COALESCE(SUM(5STAR),0), STORE, DATE
FROM `table` WHERE DATE >= '2012-02-24' GROUP BY TOTAL

答案 1 :(得分:8)

TRY

SELECT
       IFNULL(SUM(TOTAL), 0) AS total,
       IFNULL(SUM(5STAR), 0) AS FiveStar, 
       STORE,
       DATE
FROM `table`
WHERE DATE >= '2012-02-24'
GROUP BY TOTAL

Reference

答案 2 :(得分:0)

我认为在PHP端处理空结果集会更容易(计算返回的行)。如果要在数据库中处理它,则应创建存储过程。

DELIMITER $$

CREATE PROCEDURE `mc`.`new_routine` (IN DT DATETIME)
BEGIN

IF EXISTS (SELECT 1 FROM `table` WHERE DATE >= @DT)
THEN
    SELECT SUM(TOTAL) AS SumTotal, SUM(5STAR) AS Sum5Star, STORE, `DATE`
    FROM `table`
    WHERE DATE >= @DT
    GROUP BY TOTAL;
ELSE
    SELECT 0 AS SumTotal, 0 AS Sum5Star, NULL AS STORE, NULL AS `DATE`;
END IF;

END