You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MySQL及Laravel中统计每行指定列的非空字段数量

统计行内非空字段数量实现方案

1. MySQL原生语句实现

注意你给出的示例中空值为**空字符串""**而非NULL,如果你的场景中还存在NULL的情况,可自行补充IS NOT NULL判断条件。
查询语句如下:

SELECT 
    ID,
    (
        IF(Col1 != '', 1, 0) + 
        IF(Col2 != '', 1, 0) + 
        IF(Col3 != '', 1, 0) + 
        IF(Col4 != '', 1, 0) + 
        IF(Col5 != '', 1, 0)
    ) AS non_empty_count
FROM 你的表名;

执行后返回的non_empty_count字段就是对应行的非空字段数量,和你预期的结果完全匹配:ID为1的行返回2,ID为2的行返回3。

2. Laravel 实现

2.1 查询构造器(Query Builder)实现

采用参数绑定写法避免SQL注入风险:

<?php
use Illuminate\Support\Facades\DB;

$result = DB::table('你的表名')
    ->selectRaw(
        'ID, (IF(Col1 != ?, 1, 0) + IF(Col2 != ?, 1, 0) + IF(Col3 != ?, 1, 0) + IF(Col4 != ?, 1, 0) + IF(Col5 != ?, 1, 0)) as non_empty_count',
        ['', '', '', '', '']
    )
    ->get();

2.2 Eloquent 实现

假设对应表的模型为App\Models\YourModel,写法如下:

<?php
use App\Models\YourModel;

$result = YourModel::selectRaw(
    'ID, (IF(Col1 != ?, 1, 0) + IF(Col2 != ?, 1, 0) + IF(Col3 != ?, 1, 0) + IF(Col4 != ?, 1, 0) + IF(Col5 != ?, 1, 0)) as non_empty_count',
    ['', '', '', '', '']
)
->get();

如果你的数据量较小,也可以在模型层定义访问器实现,无需在SQL层面处理:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    // 追加非空统计字段到模型实例
    protected $appends = ['non_empty_count'];

    public function getNonEmptyCountAttribute()
    {
        $checkColumns = ['Col1', 'Col2', 'Col3', 'Col4', 'Col5'];
        $count = 0;
        foreach ($checkColumns as $col) {
            if ($this->getAttribute($col) !== '' && $this->getAttribute($col) !== null) {
                $count++;
            }
        }
        return $count;
    }
}

定义后直接查询模型即可获取统计值:

$rows = YourModel::all();
// 遍历取值即可
foreach ($rows as $row) {
    echo $row->non_empty_count;
}

内容的提问来源于stack exchange,提问作者Vince

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:54:04