本文介绍了如何使用MySQL有条件地处理零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在MySQL中,此查询可能会抛出被零除的错误:
In MySQL, this query might throw a division by zero error:
SELECT ROUND(noOfBoys / noOfGirls) AS ration
FROM student;
如果noOfGirls
为0
,则计算将失败.
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有条件地处理零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!