How to conditionally handle division by zero with MySQL

前端 未结 7 830
春和景丽
春和景丽 2020-12-28 16:01

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

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

If noOfGirls

7条回答
  •  别那么骄傲
    2020-12-28 16:49

    You can use this (over-expressive) way:

    select IF(noOfGirls=0, NULL, round(noOfBoys/noOfGirls)) as ration from student;
    

    Which will put out NULL if there are no girls, which is effectively what 0/0 should be in SQL semantics.

    MySQL will anyway give NULL if you try to do 0/0, as the SQL meaning fo NULL is "no data", or in this case "I don't know what this value can be".

提交回复
热议问题