【问题标题】:I need to show all data form pinjaman_id but only last data in every pinjaman_id form database我需要显示来自 pinjaman id 的所有数据,但只显示数据库中每个 pinjaman id 中的最后一个数据
【发布时间】:2019-11-08 01:16:06
【问题描述】:

我正在使用 laravel,我想根据 pinjaman_id 显示所有最后的数据,这意味着我只需要 pinjaman_id 的最后一个数据,所以 pinjaman_id 不能显示重复,我只需要最后一个,并显示所有最后的数据不同的pinjaman_id

$pinjaman = DB::table('invoice')->where('pinjaman_id', 67)->orderBy('tgl_tempo', 'desc')->first();

如果我使用它,它只显示 pinjaman_id = 67 中的最后一个数据,我需要显示它们,但只显示基于 tgl_tempo desc 的最后一个数据

$pinjaman = DB::table('invoice')->where('pinjaman_id', ??)->orderBy('tgl_tempo', 'desc')->first();

这是我的数据库图片

【问题讨论】:

    标签: database laravel laravel-query-builder


    【解决方案1】:

    试试这个

    $query = "select * from invoice where id IN (select MAX(id) from invoice where user_id = :userId group by pinjaman_id) order by tgl_tempo desc "; 
    
    $result = DB::select(DB::raw($query),['userId' => 1]);
    

    【讨论】:

      【解决方案2】:

      您必须使用原始查询来获取正确的数据,然后使用 UNION ALL 来获取其他数据

      $results = DB::select("(SELECT * FROM invoice WHERE pinjaman_id= 67 order by tgl_tempo DESC limit 1) UNION ALL (SELECT * FROM invoice WHERE pinjaman_id != 67)") ;
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 2016-03-27
        • 1970-01-01
        • 2012-11-17
        相关资源
        最近更新 更多