简体   繁体   English

简单的SQL案例问题 - NULL时返回0

[英]Simple SQL case issue - returning 0 when NULL

Apparently NUMBER + NULL returns NULL in SQL. 显然NUMBER + NULL在SQL中返回NULL。 So I need it to add 0 instead of NULL but this isn't working, I'm getting a syntax error. 所以我需要它添加0而不是NULL,但这不起作用,我收到语法错误。 I'm looking at the docs and this is what it says to do so I'm not sure... 我正在查看文档,这就是它所说的,所以我不确定......

SELECT sku, (qty + (SELECT(CASE qty WHEN IS NULL THEN 0 ELSE qty END)
                    FROM other WHERE sku = Sheet1.sku LIMIT 1)) as qty
FROM Sheet1 WHERE sku != '' 
ORDER BY sku ASC

You have an error in your SQL syntax; 您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法

'IS NULL THEN 0 ELSE qty END) FROM other WHERE sku = Sheet1.sk

You're really close. 你真的很亲密

Case qty When NULL Then 0 else qty END

The IS Null is a Where Clause Convention. IS Null是Where子句约定。 You can also use Coalesce: 您也可以使用Coalesce:

Select Coalesce(qty, 0)

Coalesce returns the 1st non-null of it's parameter list. Coalesce返回其参数列表的第1个非null值。 So if qty is Null you get 0, otherwise you get qty. 因此,如果数量为空,则得到0,否则得到数量。

使用此语法将NULL替换为0:

select COALESCE(qty,0)...

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

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