简体   繁体   中英

CASE WHEN NULL in MySQL

I'm trying to set item quantity to 0 if it's NULL in "item_to_inv"

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

What's wrong in following CASE WHEN statement?

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 ).

You can make the query return 0 for those ids by changing your query to:

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.

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

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. 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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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