How to conditionally handle division by zero with MySQL

前端 未结 7 832
春和景丽
春和景丽 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:57

    Yes, you can do a case:

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

    But you probably want:

    select case when noOfGirls=0 then 1 
           else  round(noOfBoys/noOfGirls) end as ration 
    from student;
    
    0 讨论(0)
提交回复
热议问题