mysql 统计非空字段数,计数非空字段mysql

I want to count how many fields of a specific fieldset are empty in mysql, I've found some examples but they all go through the whole table.

Basically I have 8 fields,

listing_photo_1 to listing_photo_8, I want to get the count of how many of them are filled.

I tried:

$result=mysql_query("SELECT count(*) as total from listings

WHERE listing_photo_1 IS NOT NULL AND

listing_photo_2 IS NOT NULL AND

listing_photo_3 IS NOT NULL AND

listing_photo_4 IS NOT NULL AND

listing_photo_5 IS NOT NULL AND

listing_photo_6 IS NOT NULL AND

listing_photo_7 IS NOT NULL AND

listing_photo_8 IS NOT NULL AND

pmpid = '$pmpid'");

$data=mysql_fetch_assoc($result);

echo $data['total'];

Which results in: 1

To clarify the result I am expecting:

listing_photo_1: filled

listing_photo_2: filled

listing_photo_3: filled

listing_photo_4: empty

listing_photo_5: empty

listing_photo_6: empty

listing_photo_7: empty

listing_photo_8: empty`

The result should be 3

解决方案

You code attempts to count the number of rows where all the fields a not null. You should be using is not null rather than just not null.

To count the number of fields, use this:

SELECT sum((listing_photo_1 IS NOT NULL) +

(listing_photo_2 IS NOT NULL) +

(listing_photo_3 IS NOT NULL) +

(listing_photo_4 IS NOT NULL) +

(listing_photo_5 IS NOT NULL) +

(listing_photo_6 IS NOT NULL) +

(listing_photo_7 IS NOT NULL) +

(listing_photo_8 IS NOT NULL)

) as total

from listings

WHERE pmpid = '$pmpid';

To count the number of rows:

SELECT count(*) as total

from listings

WHERE listing_photo_1 IS NOT NULL AND

listing_photo_2 IS NOT NULL AND

listing_photo_3 IS NOT NULL AND

listing_photo_4 IS NOT NULL AND

listing_photo_5 IS NOT NULL AND

listing_photo_6 IS NOT NULL AND

listing_photo_7 IS NOT NULL AND

listing_photo_8 IS NOT NULL AND

pmpid = '$pmpid'";

EDIT:

If they are blank, use logic like this:

SELECT sum((listing_photo_1 IS NOT NULL and listing_photo_1 <> '') +

(listing_photo_2 IS NOT NULL and listing_photo_2 <> '') +

(listing_photo_3 IS NOT NULL and listing_photo_3 <> '') +

(listing_photo_4 IS NOT NULL and listing_photo_4 <> '') +

(listing_photo_5 IS NOT NULL and listing_photo_5 <> '') +

(listing_photo_6 IS NOT NULL and listing_photo_6 <> '') +

(listing_photo_7 IS NOT NULL and listing_photo_7 <> '') +

(listing_photo_8 IS NOT NULL and listing_photo_8 <> '')

) as total

from listings

WHERE pmpid = '$pmpid';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值