dongxiangshen7916 2015-03-16 01:41
浏览 380

获取非空值的计数

I've looked everywhere on how to do this and it seems like an awful long approach to output 1 number.

This is the layout of my database:

UserId         Info1    Info2    Info3   Info4   Info5   Info6   Info7
-------------------------------------------------------------------------------

user1      |   xyz   |         | abc   |  xyz  |       | abc   | 
user2      |         |  abc    |       |  def  |  ghi  | wxy   | jkl

What i want to do is return a number for example: 

User1 has completed 4 Tasks 
User2 has completed 5 Tasks       

There are 95 columns in this row so as you can understand it would be a real pain to count each one individually. However i only want to count the ones that are not empty and return a number.

<?
$sql="SELECT * FROM builder WHERE userid = '".$userid."' IS NOT NULL";
$query=mysql_query($sql);    
$num=mysql_num_fields($query);
echo $num;?>

This outputs how many rows there are in total regardless of whether they are empty or not so the number is always the same which isn't what I want.

Any suggestions?

  • 写回答

2条回答

  • duanjiwei1283 2015-03-16 01:44
    关注

    You can count the values in MySQL using this construct:

    select ((info1 is not null) +
            (info2 is not null) +
            (info3 is not null) +
            (info4 is not null) +
            (info5 is not null) +
            (info6 is not null) +
            (info7 is not null)
           ) as NumNotNull
    

    MySQL treats boolean expressions as integers, in a numeric context. TRUE is "1", so you can just add them up to get the total that match.

    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用