如何使用PHP对MySQL两个表中的非空值计数进行求和
问题描述
我在MySQL数据库中有两个表,分别为table_1和table_2。
两张表均包含4个用户相关字段:
user_1、user_2、user_3、user_4


现在我需要通过PHP提取两张表中的非空值并统计总数量,首先我使用如下查询统计table_1的非空值:
<?php $query1 = " select * from table_1 where user_1!='' and user_1 is not null union all select * from table_1 where user_2!='' and user_2 is not null union all select * from table_1 where user_3!='' and user_3 is not null union all select * from table_1 where user_4!='' and user_4 is not null ";
执行查询后我使用mysqli_num_rows统计条目数,得到的正确结果为3。
我使用相同逻辑统计table_2的非空值:
<?php $query2 = " select * from table_2 where user_1!='' and user_1 is not null union all select * from table_2 where user_2!='' and user_2 is not null union all select * from table_2 where user_3!='' and user_3 is not null union all select * from table_2 where user_4!='' and user_4 is not null ";
得到的正确统计结果为2。
但当我将两个统计结果相加时:
$count1 = mysqli_num_rows($data1); $count2 = mysqli_num_rows($data2); $total = $count1+$count2;
得到的结果要么是1,要么是其他异常值,请问该如何修复这个问题?
解决方案
问题根因
异常结果主要有两个核心原因:
- 同一个MySQL连接下执行多次查询时,没有主动释放前一次查询的结果集,后一次查询会覆盖前一次的结果资源,导致
mysqli_num_rows取到错误值。 - 没有增加查询错误判断逻辑,如果某次查询执行失败,
mysqli_query会返回布尔值false,传入mysqli_num_rows后会返回null,做算术运算时null会自动转为0或1,最终得到异常结果。
另外你当前的统计逻辑性能极低:拉取全表数据到PHP侧统计行数,表数据量大时会占用大量内存和网络IO,完全可以直接在数据库侧完成统计。
临时修复方案
如果要保留你原来的查询逻辑,只需要补充结果集释放和错误判断即可:
// $conn为你的数据库连接实例 $result1 = mysqli_query($conn, $query1); $count1 = $result1 ? mysqli_num_rows($result1) : 0; // 释放第一个结果集 mysqli_free_result($result1); $result2 = mysqli_query($conn, $query2); $count2 = $result2 ? mysqli_num_rows($result2) : 0; // 释放第二个结果集 mysqli_free_result($result2); $total = $count1 + $count2;
最优重构方案
直接通过SQL在数据库侧完成统计,仅返回最终统计值,性能提升明显,也完全避免结果集冲突问题:
$totalSql = " SELECT ( -- 统计table_1的非空非空字符串的字段总数量 (COUNT(NULLIF(user_1, '')) + COUNT(NULLIF(user_2, '')) + COUNT(NULLIF(user_3, '')) + COUNT(NULLIF(user_4, ''))) + -- 统计table_2的非空非空字符串的字段总数量 (SELECT COUNT(NULLIF(user_1, '')) + COUNT(NULLIF(user_2, '')) + COUNT(NULLIF(user_3, '')) + COUNT(NULLIF(user_4, '')) FROM table_2) ) AS total FROM table_1 "; $res = mysqli_query($conn, $totalSql); $total = mysqli_fetch_assoc($res)['total'];
逻辑说明:COUNT()函数会自动忽略NULL值,NULLIF(字段, '')会把空字符串转为NULL,因此统计的结果就是所有字段非空且不为空字符串的总数量,和你之前的统计逻辑结果完全一致。
内容的提问来源于stack exchange,提问作者user173819
相关产品推荐
相关产品推荐

