暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PG的空值相加如何实现

yanzongshuaiDBA 2022-04-11
1083

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

    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 行记录)
    复制

    看下加的结果:

      postgres=# select id1+id2 from t3;
      ?column?
      ----------
      3



      (4 行记录)
      复制

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

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

        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值相关的加法计算。

        文章转载自yanzongshuaiDBA,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

        评论