Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-01 12:59:33
Original
1187 people have browsed it

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

1 表中的数据

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

\

2 有问题的运算语句

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

Copy after login

\

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
Copy after login

\

 

4 建议


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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!