且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 23:03:07

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

I think it would be easier to handle the empty result set on the PHP side (count the returned rows). If you want to handle it in the database, you should create a stored procedure.

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