简体   繁体   中英

How to handle division by 0 for select statements?

I do this

    $query4 = "(
                 SELECT count(*) 
                 FROM checklist c
                 JOIN task AS t ON t.id = c.task_id AND t.active=1
                 WHERE c.placement_id = m.id
               ) / (
                 SELECT count(*) 
                 FROM task 
                 WHERE active = 1
               )";

in php which I stick in a bigger sql string. The problem is the second select above, may be 0. In the case that it is 0 I want the division to be automatically a 1 (like turn the whole query4 into a 1).

Does anyone know how to do this?

Thanks.

In your case, the simplest change is probably this:

$query4 = "(
             SELECT count(*) 
             FROM checklist c
             JOIN task AS t ON t.id = c.placement_id AND t.active=1
             WHERE c.placement_id = m.id
           ) / (
             SELECT (case when count(*) > 0 then count(*) end)
             FROM task 
             WHERE active = 1
           )";

This will replace 0 values with NULL -- so the division will return NULL instead of an error.

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