解決mysql sum求和返回null問題或IFNULL應用

問題描述:sum求和要求返回float(或 integer或double等)類型,但當數據庫不存在任何符合求和記錄時,sum返回null,報類型綁定錯誤異常(mybatis:

org.apache.ibatis.binding.BindingException: Mapper method 'com.danaaa.cm.dao.AgentWithdrawalMapper.getTotalByWeek attempted to return null from a method with a primitive return type (float).
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:69)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
    at com.sun.proxy.$Proxy222.getTotalByWeek(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy223.getTotalByWeek(Unknown Source)

解決辦法:IFNULL(SUM(transfer_amount),0),當數據庫不存在任何符合求和記錄時,sum返回0

例如:SELECT IFNULL(SUM(transfer_amount),0)   FROM cm_agent_withdrawal  WHERE  transfer_status in (1,2,3)


mysql IFNULL(expr1,expr2)

如果 expr1 不是 NULL,IFNULL() 返回 expr1,否則它返回 expr2。

IFNULL()返回一個數字或字符串值,取決於它被使用的上下文環境。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章