【问题标题】:Laravel get multple columns using distinct on one of themLaravel 在其中一个上使用 distinct 获取多个列
【发布时间】:2017-08-26 05:46:13
【问题描述】:

人脸表结构:

id
photo_id
person_id

一个人可以出现在许多照片中。我想为每个人返回第一张照片。我试过了:

$faces = Face::select('person_id','photo_id')
        ->groupBy('person_id','photo_id')
        ->whereNotNull('person_id')
        ->get()
        ->toArray();

这会返回不同的组合,即每个人的所有照片。 Distinct 只会返回我选择的不同列。我需要两个都退回。

【问题讨论】:

    标签: mysql laravel-5 eloquent


    【解决方案1】:

    如果您只想返回每个人的第一张照片,则仅按人分组并返回照片 ID 的最小值。在sql中看起来如下:

    select person_id, min(photo_id)
    from yourtable
    group by person_id
    

    我对 laravel 不是很好,但我尝试了查询的样子(你并不真的需要 person id is not null 标准):

    $faces = Face::select('person_id',DB::raw('min(photo_id) as photo_id')
            ->groupBy('person_id')
            ->get()
            ->toArray();
    

    【讨论】:

      猜你喜欢
      • 2010-12-19
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2013-09-16
      • 2021-11-01
      相关资源
      最近更新 更多