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 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊