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.*']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架