简体   繁体   English

当查询结果为空时,如何强制MySQL查询返回0?

[英]How to force a MySQL query to return a 0 when the result of query is nothing?

I have the following query: 我有以下查询:

SELECT 
SUM(quantity) AS qt
FROM 
stockMove
WHERE
date_mov >= '2019-04-01'
AND
date_mov <= '2019-04-30'
AND
ProductCode = '000807'
GROUP BY 
ProductCode 

If a have no movement of this product in this date range, the query returns nothing, but I need that to return 0. 如果在此日期范围内该产品没有动静,则查询将不返回任何内容,但我需要返回0。

I already try: 我已经尝试了:

SELECT SUM(quantity) AS qt, COALESCE(quantity, 0) SELECT SUM(quantity)AS qt,COALESCE(quantity,0)

and

SELECT SUM(quantity) AS qt, IFNULL(quantity, 0) SELECT SUM(quantity)AS qt,IFNULL(quantity,0)

but the query still returns 0 rows. 但查询仍返回0行。

Is there a way to resolve my issue? 有办法解决我的问题吗?

Thanks guys. 多谢你们。

如下使用

SELECT COALESCE(SUM(quantity),0) AS qt

In your case, just remove the GROUP BY and use COALESCE() : 就您而言,只需删除GROUP BY并使用COALESCE()

SELECT COALESCE(SUM(quantity), 0) AS qt
FROM stockMove
WHERE date_mov >= '2019-04-01' AND date_mov <= '2019-04-30' AND
      ProductCode = '000807';

An aggregation query with no GROUP BY always returns one row, even when no rows match. 没有GROUP BY的聚合查询总是返回一行,即使没有行匹配也是如此。 The returned value is NULL -- which is where the COALESCE() comes in. 返回值是NULL这是COALESCE()进入的地方。

With the GROUP BY , the query returns no rows at all. 使用GROUP BY ,查询根本不返回任何行。 Can't convert nothing into a 0 . 无法将任何内容都转换为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM