Heim  >  Artikel  >  Datenbank  >  Mysql整数运算NULL值处理注意点_MySQL

Mysql整数运算NULL值处理注意点_MySQL

WBOY
WBOYOriginal
2016-06-01 12:59:331155Durchsuche

CleverCode最近在导出报表的时候,在整数做减法的时候,发现整数减去null得到是null。这是一个细节问题,希望大家以后注意。

1 表中的数据

total,used都是整形,允许为空。

\

2 有问题的运算语句

减法问题
select 
	id,
	total,
	used,
	(total - used) as have 
from test_table


\

 

 

3 正确的写法

 

使用ifnull,来处理null。
select 
	id,
	ifnull(total,0) as total,
	ifnull(used,0) as used,
	(ifnull(total,0) - ifnull(used,0)) as have 
from test_table

\

 

4 建议


1) 在设计表的时候,如果发现这列是需要运算的列,建议设置默认值,比如0; 2) 在整形列的运算的时候,不管是加,减,乘,除等。都需要使用ifnull,对列进行处理。否则报表数据就会错。
这些都是细节小问题,大家一看就能明白,希望大家在细节上注意,否则一份财务表报计算出错了,那后果是很严重的!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn