选择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)。
全表结构:
答案 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
答案 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