前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PG的空值相加如何实现

PG的空值相加如何实现

作者头像
yzsDBA
发布2022-04-27 15:28:32
2.2K0
发布2022-04-27 15:28:32
举报
文章被收录于专栏:PostgreSQL研究与原理解析

PostgreSQL数据库中,对于NULL值相加的处理:任何数值和NULL相加都得NULL。

代码语言:javascript
复制
postgres=# create table t3(id1 int,id2 int);
CREATE TABLE
postgres=# insert into t3 select 1,2;
INSERT 0 1
postgres=# insert into t3 select 1,NULL;
INSERT 0 1
postgres=# insert into t3 select NULL,NULL;
INSERT 0 1
postgres=# insert into t3 select NULL,3;
INSERT 0 1
postgres=# select *from t3;
 id1 | id2
-----+-----
   1 |   2
   1 |
     |
     |   3
(4 行记录)

看下加的结果:

代码语言:javascript
复制
postgres=# select id1+id2 from t3;
 ?column?
----------
        3



(4 行记录)

可以看到只要有一个参数是NULL,那么加的结果就是NULL。那么这个计算是如何实现的呢?

从前文可以了解到操作符“+”的实现机制,真正执行是在ExecInterpExpr函数中:

代码语言:javascript
复制
ExecInterpExpr
  EEO_CASE(EEOP_FUNCEXPR_STRICT)//操作符函数的执行
  {
    FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
    NullableDatum *args = fcinfo->args;
    int      argno;
    Datum    d;

    /* strict function, so check for NULL args */
    for (argno = 0; argno < op->d.func.nargs; argno++)
    {
      if (args[argno].isnull)
      {
        *op->resnull = true;//只要有一个参数是NULL,就标记resnull为true
        goto strictfail;
      }
    }
    fcinfo->isnull = false;
    d = op->d.func.fn_addr(fcinfo);
    *op->resvalue = d;
    *op->resnull = fcinfo->isnull;

strictfail:
    EEO_NEXT();
  }
  ...
  EEO_CASE(EEOP_ASSIGN_TMP_MAKE_RO)
  {
    int  resultnum = op->d.assign_tmp.resultnum;
    //上一步的resnull值传递到resultslot中,标记该slot是一个NULL
    resultslot->tts_isnull[resultnum] = state->resnull;
    if (!resultslot->tts_isnull[resultnum])
      resultslot->tts_values[resultnum] =
        MakeExpandedObjectReadOnlyInternal(state->resvalue);
    else
      resultslot->tts_values[resultnum] = state->resvalue;
    EEO_NEXT();
  }

这样就完成了NULL值相关的加法计算。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-04-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 yanzongshuaiDBA 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档