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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作