【问题标题】:Get data & Ignore null value when using group by in laravel [duplicate]在laravel中使用group by时获取数据并忽略空值[重复]
【发布时间】:2021-12-22 16:54:26
【问题描述】:

我想按基于content_related_group 的数据进行分组。但是有一种情况 content_related_group 为空,我不希望它对空值的数据进行分组。

我试过这样:

$products = DB::table('product')
        ->select('*', DB::raw('count(*) as total'))
        ->orderBy('created_at', 'desc')
        ->groupBy('content_related_group')  
        ->paginate(9);

它正在工作,但它将空数据分组为一个。我不想要它,我想要的是从数据库中获取所有数据,并且只将具有相同content_related_group的数据分组为一个。

示例数据:

id   |   content_related_group
1    |   content_1
2    |   content_1
3    |   null
4    |   null

结果(空数据保持相互分离&相同的content_related_group被分组:

id   |  content_related_group
1    | content_1
2    | null
3    | null

有可能吗?谢谢

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    如果你想删除空行,试试这个:

    $products = DB::table('product')
            ->select('*', DB::raw('count(*) as total'))
            ->whereNotNull('content_related_group')  
            ->orderBy('created_at', 'desc')
            ->groupBy('content_related_group')  
            ->paginate(9);
    

    如果您想将空值分组到一行,请尝试此操作

    $x_products   =   DB::table('product')->whereNull('content_related_group');
    
    $products = DB::table('product')
            ->whereNotNull('content_related_group')
            ->union($x_products)
            ->select('*', DB::raw('count(*) as total'))
            ->orderBy('created_at', 'desc')
            ->groupBy('content_related_group')  
            ->paginate(9);
    

    【讨论】:

    • 谢谢,但它通过跳过具有空值的数据来忽略空值,我想保留具有空值的数据并将其他数据与相同的 content_related_group 分组
    • 嗯,检查我的更新答案
    • 我收到错误SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: select count(*) as aggregate from ((select *, count(*) as total from `product` where `content_related_group` is not null group by `content_related_group`) union (select * from `product` where `content_related_group` is null) order by `created_at` desc) as `temp_table`)
    • 可以发布一些虚拟数据并提供您期望的结果@Catto
    • @ManojKiranAppathurai 我在帖子中提供了它,示例是数据库中的数据。结果就是我想要的
    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多