简体   繁体   English

如何处理select语句的除以0?

[英]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. 在PHP中,我坚持使用更大的sql字符串。 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). 问题是上面的第二个选择,可能是0.在它为0的情况下,我希望除法自动为1(就像将整个query4转换为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. 这将用NULL替换0值 - 因此除法将返回NULL而不是错误。

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

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