我想计算一下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:empty`
结果应为3
答案 0 :(得分:1)
WHERE listing_photo_1 IS NOT NULL AND listing_photo_2 IS NOT NULL....
修改强>
如果你需要获得每列的非空计数,你可以这样做
SELECT count(listing_photo_1),count(listing_photo_2),....count(listing_photo_8)
from listings where pmpid = id
Count(column)
将仅计算非空值。
答案 1 :(得分:1)
您的代码尝试计算所有字段为非空的行数。您应该使用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';