小编典典

计数非空字段mysql

sql

我想计算一个特定字段集的多少字段在mysql中为空,我找到了一些示例,但它们都遍历整个表。

基本上我有8个领域

listing_photo_1到listing_photo_8,我想获取其中已填充的数量。

我试过了:

$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'];

结果是: 1

为了澄清我期望的结果:

listing_photo_1:已填满

listing_photo_2:已填满

listing_photo_3:已填满

listing_photo_4:为空

listing_photo_5:为空

listing_photo_6:为空

listing_photo_7:为空

listing_photo_8:为空`

结果应该是 3


阅读 214

收藏
2021-04-14

共1个答案

小编典典

您编写代码尝试计算所有字段都不为null的行数。您应该使用is not null而不是仅仅使用not null

要计算字段数,请使用以下命令:

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';

要计算行数:

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'";

编辑:

如果它们为空,请使用如下逻辑:

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';
2021-04-14