如何使用MySQL有条件地处理零除 [英] How to conditionally handle division by zero with MySQL

查看:342
本文介绍了如何使用MySQL有条件地处理零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL中,此查询可能会抛出被零除的错误:

In MySQL, this query might throw a division by zero error:

SELECT ROUND(noOfBoys / noOfGirls) AS ration
FROM student;

如果noOfGirls0,则计算将失败.

If noOfGirls is 0 then the calculation fails.

处理此问题的最佳方法是什么?

What is the best way to handle this?

noOfGirls等于0时,我想有条件地将noOfGirls的值更改为1.

I would like to conditionally change the value of noOfGirls to 1 when it is equal to 0.

有更好的方法吗?

推荐答案

是的,您可以做一个案例:

Yes, you can do a case:

select case when noOfGirls=0 then noOfBoys 
       else  round(noOfBoys/noOfGirls) end as ration 
from student;

但是您可能想要:

select case when noOfGirls=0 then 1 
       else  round(noOfBoys/noOfGirls) end as ration 
from student;

这篇关于如何使用MySQL有条件地处理零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆