当要求某个值和null之间的差异时,mysql返回null

时间:2011-05-18 06:34:28

标签: c++ mysql

在我的表中我有3列 id,somevalue(float),当前时间戳

下面的

代码搜索今天日期的最新值,并使用同一周的星期一值减去该值。但是我没有在本周的星期一存储任何值,所以它目前是空的。但是下面代码的结果应该是某些值不为空?不明白怎么可能。请解释一下。

select(SELECT power FROM newdb.newmeter
where date(dt)=curdate() order by dt desc limit 1)-
(select Power from newdb.newmeter
where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));

因为我正在阅读类似的问题 - 答案它看起来像你在mysql中用null做的任何事情都是null是真的吗? 如果是,我该怎么解决这个

更新: 我试过这个,但没有工作 select sum(amount) - coalesce(sum(due),0)

只是想为此添加更多内容 我正在调用querydb作为以下c ++中的mysql

bool Querydb(char *query, double Myarray[1024])
{
   //snip//

    if (mysql_query(conn, query)) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    return 0;
    }

    else {
    res = mysql_use_result(conn);
    //output table name
    //printf("MySQL Tables in mysql database:\n");

    //checking for null value in database
    while((row = mysql_fetch_row(res))==NULL){
        printf("ERROR_____NULL VALUE IN DATABASE  ");
        return 0;
    }

    //if not null then ...
    while ((row = mysql_fetch_row(res)) != NULL){
        printf("rows fetched %s\n", row[0]);
        sprintf(buffer,"%s",row[0]);
       value1 = atof(buffer);
        Myarray[i]=value1;
        //printf("Myarray in sql for daybutton = %f\n",Myarray[i]);
        i++;
        }
    i=0;
    //for(i=0;i<5;i++){
    //    printf("mya arr in sqlfunction = %f\n",Myarray[i]);}
    return 1;
    }
    printf("if here then....where??\n");

   //close connection
   // mysql_free_result(res);
   //return 0;
}

当数据库为null但不能使用此查询时,上述函数可以正常使用不同的查询

  select(SELECT power FROM newdb.newmeter
    where date(dt)=curdate() order by dt desc limit 1)-
    (select Power from newdb.newmeter
    where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));

即使答案是NULL,它也会返回1 ...

3 个答案:

答案 0 :(得分:3)

请参阅有关使用NULL值的手册。他们受到特别对待http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

答案 1 :(得分:3)

您希望它具有什么价值?这并不是特别针对MySQL - 涉及空操作数(包括比较)的操作在大多数SQL方言中都有空结果。

您可能希望使用COALESCE()来提供“默认”值,该值在您的真实目标值为空时使用。

答案 2 :(得分:0)

工作将是

select(SELECT power FROM newdb.newmeter
where date(dt)=curdate() order by dt desc limit 1)-
(select COALESCE(Power,0) from newdb.newmeter
where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));