doulu8341 2015-01-05 16:17
浏览 351
已采纳

如何使用Eloquent和MySQL按最后一个ID排序分组结果?

I tried this query but it only order id column, rest is not.

$chapters = Test::select(DB::raw('*, max(id) as id'))
        ->groupBy('id_equip')
        ->orderBy('id', 'asc')
        ->get();
  • 写回答

1条回答 默认 最新

  • dshdsh2016 2015-01-05 21:00
    关注

    In MySQL when using group by you can't rely on order by clause (it won't work as you expect, ie. it will not order the results in groups, but rather return random row from the group).

    So in order to achieve what you want, you need a subquery or join:

    // assuming tests table, group by id_equip, order by id
    SELECT * FROM tests WHERE id = (
       SELECT MAX(id) FROM tests as t WHERE t.id_equip = tests.id_equip
    ) ORDER BY id
    
    SELECT * FROM tests 
       JOIN (SELECT MAX(id) as id FROM tests ORDER BY id DESC) as sub
          ON sub.id = tests.id
    

    This will get the highest id for each id_equip and return whole row for each of them.


    Now, in eloquent I suggest first approach, if you want it to look more intuitive:

    Test::where('id', function ($sub) {
       // subquery
       $sub->selectRaw('max(id)')
           ->from('tests as t')
           ->where('t.id_equip', DB::raw('tests.id_equip'));
    // order by
    })->orderBy('id', 'desc')->get();
    

    but 2nd appreach is probably the way if you have big table to scan (in terms of performance):

    Test::join( DB::raw(
        '(select max(id) as id from tests group by id_equip order by id desc) sub'
      ), 'sub.id', '=', 'posts.id')
      ->get(['tests.*']);
    

    Here you need to set order by clause inside the raw join statement.

    You could also build that join subquery with the builder if you like:

    $sub = Test::selectRaw('max(id)')
            ->groupBy('id_equip')
            ->orderBy('id', 'desc')
            ->toSql();
    
    Test::join( DB::raw(
        "({$sub}) as sub"
      ), 'sub.id', '=', 'posts.id')
      ->get(['tests.*']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码