groupBy和orderBy Laravel获得更高的价值

时间:2017-03-21 07:45:18

标签: php sql laravel

分组和排序查询结果时遇到问题。 这是我的数据

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|     46 | 3         |  31      | B      | C     |
|  18393 | 3         |  31      | U      | A     |
+--------+-----------+----------+--------+-------+

这是我的查询

DB::table('krs')->select('id_krs','id_mhs_pt','id_kelas','status','nilai')
    ->where('id_mhs_pt',3)->groupBy('id_kelas')->orderBy('nilai','asc')->get();

当我运行查询时,结果是:

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|     46 | 3         |  31      | B      | C     |
+--------+-----------+----------+--------+-------+

我想要的结果是

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|  18393 | 3         |  31      | U      | A     |
+--------+-----------+----------+--------+-------+

因为id_krs 18393具有比id_krs 46更高的nilai(得分)(两者都使用相同的id_kelas)。我试图将顺序更改为asc或desc,但结果仍然相同。怎么做到的?感谢'!小号

1 个答案:

答案 0 :(得分:0)

问题是你遗失了order上的group by,所以你必须使用临时表来获得每个nilai的最小id_kelas,然后按顺序加入获取其他列:

DB::table('krs')
    ->select('id_krs', 'id_mhs_pt', 'id_kelas', 'status', 'nilai')
    ->leftJoin(
        DB::raw('(select id_krs, min(nilai) as m_nilai FROM krs GROUP BY id_kelas) tmp'), function ($join) {
            $join
                ->on(DB::raw('tmp.id_krs'), '=', DB::raw('krs.id_krs'))
                ->on(DB::raw('tmp.m_nilai'), '=', DB::raw('krs.nilai'));
        }
    )
    ->where('id_mhs_pt', 3)
    ->orderBy('nilai', 'asc')
    ->get();