如何从查询生成器上的每个组中获取多个数据 laravel

How to get the several data from each group on query builder laravel

a16s table

id  p_id u_id   time
1   1       2   0
2   1       1   1
3   1       5   2
4   1       6   3
5   1       7   4
6   2       2   2
7   2       3   1
8   2       1   0
9   3       2   11
10  3       4   8
11  3       8   15

我想得到 每组的前两个数据按时间排序

p_id u_id time
1     2   0
1     1   1
2     1   0
2     3   1
3     4   8
3     2   11

我尝试查询

  $result = DB::table('a16s')

            ->select ('p_id','u_id','time'))
            ->orderBy('time', 'desc')
            ->groupBy('p_id')
            ->get();

    echo '<pre>' ;
    print_r($result);

我收到错误 SQLSTATE[42000]:语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 子句中并且包含非聚合列...

我可以使用groupby两次吗?我想得到这个结果用于 jquery 数据 table.

来自数据库

id  p_id    u_id    approve time
1   1          1    1       1
2   1          2    1       2
3   1          3    1       3
4   1          4    0       4
5   1          5    0       5
6   2          1    0       1
7   2          2    1       2
8   2          5    0       3
9   2          6    0       4
10  3          2    1       1
11  3          5    1       2
12  3          8    1       3

获得table

试试这个

$result = DB::table('a16s')
            ->select('p_id', 'u_id', 'time')
            ->orderBy('time', 'desc')
            ->get()
            ->groupBy('p_id')
            ->map(function ($deal) {
                return $deal->take(2);
            });

对于您的 SQL 版本,u_id 需要从 select 中删除或添加到 GROUP BY 子句中。

查看此MySql doc了解更多信息。

使用this trick:

$join = DB::table('a16s')->select('p_id')
    ->selectRaw('GROUP_CONCAT(time ORDER BY time ASC) times')->groupBy('p_id');
$sql = '(' . $join->toSql() . ') latest';
$result = DB::table('a16s')
    ->select('a16s.*')
    ->join(DB::raw($sql), function($join) {
        $join->on('a16s.p_id','=','latest.p_id');
        $join->whereBetween(DB::raw('FIND_IN_SET(`a16s`.`time`, `latest`.`times`)'), [1, 2]);
    })
    ->get();