简体   繁体   中英

How to treat null as 0 when use addition in sql with out IFNULL

I have a query which add many thing in a expression. Like this select a+b+c+d+e ... .
But some of them may be null and I want to treat null value as 0.

I know I can use IFNULL like select ifnull(a,0)+ifnull(b,0)+ifnull(c,0)+ifnull(d,0)+ifnull(e,0) , but I have many queries and this seems laboursome.

Is there some easy way like a function to achieve the same result?

As mentioned in the comments, you will need to use indeed either IFNULL or IF .

However, if you have lots of them, and you are in control of the schema, I would suggest defining your fields as .. NOT NULL DEFAULT 0 (explicit default is good). This way, you will not need IFNULL any longer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM