简体   繁体   English

在MySQL中为NULL的情况

[英]CASE WHEN NULL in MySQL

I'm trying to set item quantity to 0 if it's NULL in "item_to_inv" 我正在尝试将“ item_to_inv”中的商品数量设置为0(如果为NULL)

SELECT i.`id`
, (SELECT SUM(CASE WHEN (`quantity` < 0 OR `quantity` IS NULL) THEN 0 ELSE `quantity` END) AS `quantity` FROM `item_to_inv` WHERE `item_id` = i.`id` GROUP BY `item_id`) AS `quantity`
FROM `item` AS `i`

The following item ids: 5, 8 and 10 has not records in item_to_inv 以下项目ID: 5、8和10在item_to_inv中没有记录

What's wrong in following CASE WHEN statement? 遵循CASE WHEN语句有什么问题?

CASE WHEN (`quantity` < 0 OR `quantity` IS NULL) THEN 0

在此处输入图片说明

There is nothing wrong with the case statement, the problem is that for ids 5, 8 and 10 you are trying to sum no values which will return NULL (see the manual ). case语句没有任何问题,问题在于,对于ID 5、8和10,您试图不求和将返回NULL的值(请参阅手册 )。

You can make the query return 0 for those ids by changing your query to: 您可以通过将查询更改为以下内容,使查询针对这些ID返回0:

SELECT i.`id`
, (SELECT IFNULL(SUM(CASE WHEN (`quantity` < 0 OR `quantity` IS NULL) THEN 0 ELSE `quantity` END), 0) AS `quantity` FROM `item_to_inv` WHERE `item_id` = i.`id` GROUP BY `item_id`) AS `quantity`
FROM `item` AS `i`

使用此查询

update Your_Table_name set quantity=0 where item_to_inv IS NULL ;

The problem here is that your subquery is returning no record, so the 'when' clause isn't coming into play - there isn't a matching record. 这里的问题是您的子查询不返回任何记录,因此'when'子句不起作用-没有匹配的记录。

Restructure your query to use an outer join to return a record even where there is no match 重组查询以使用外部联接返回记录,即使没有匹配项

See http://sqlfiddle.com/#!9/e37faf/4 参见http://sqlfiddle.com/#!9/e37faf/4

SELECT i.`id`, SUM(IFNULL(ii.`quantity`, 0))
FROM  `item` AS `i`
LEFT OUTER JOIN `item_to_inv` AS ii ON ii.`item_id` = i.`id`
GROUP BY i.`id`

Sometimes MySQL doesn't understand null as blank and that's why IS NULL doesn't work. 有时MySQL无法将null理解为空白,这就是IS NULL无法正常工作的原因。 Try changing your query to this 尝试将查询更改为此

SELECT i.`id`, (SELECT SUM(CASE WHEN (`quantity` < 0 OR `quantity`='') THEN 0
ELSE `quantity` END) AS `quantity` FROM `item_to_inv` WHERE `item_id` = i.`id`
GROUP BY `item_id`) AS `quantity` FROM `item` AS `i`

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

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