PostgreSQL空值null参与运算的处理方法
在数字加减乘除运算中遇到某个字段值为空值(null)的时候,输出的结果往往会让我们失望,得不到我们所期待的数值,可以通过 coalesce方式将凡是取值为null,即空值的字段转换成默认的值进行运算,从而改善运算效果。
coalesce函数用法: coalesce(字段名,默认值),很简单吧~
演示如下: [root@dbserver ~]# su - postgres -bash-3.2$ psql music psql (9.5beta2) 输入 "help" 来获取帮助信息. music=# create table test_null(id int,num1 int,num2 int); CREATE TABLE
插入数据,有的取值为正常数字,有的则为空值null: music=# insert into test_null values(1,100,100); INSERT 0 1 music=# insert into test_null values(2,200,200); INSERT 0 1 music=# insert into test_null values(3,null,100); INSERT 0 1 music=# insert into test_null values(4,300,null); INSERT 0 1 music=# insert into test_null values(5,null,500); INSERT 0 1
查看一下表中的数据,发现null值的字段全部为空值: music=# select * from test_null; id | num1 | num2 ----+------+------ 1 | 100 | 100 2 | 200 | 200 3 | | 100 4 | 300 | 5 | | 500 (5 行记录)
直接运算查看结果,会发现凡是遇到空值的运算结果均为空: music=# select num1+num2 from test_null; ?column? ---------- 200 400 (5 行记录)
使用 coalesce函数之后便可处理null的问题: music=# select coalesce(num1,0)+coalesce(num2,0) from test_null; ?column? ---------- 200 400 100 300 500 (5 行记录)
在这里,coalesce设置的默认值为0,同样也可以设置为其他的数值,比如人体体温可以设置默认值为36,冰点为0,沸点为100等。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft