Laravel 4 Query Builder - groupBy Max Date

时间:2014-05-23 17:36:03

标签: php mysql laravel-4 greatest-n-per-group query-builder

小查询问题, 我有桌子:

id    | user_id | paper_update
------------------------------
1     |    1    | 30-5-2011
2     |    2    | 30-5-2012
3     |    3    | 30-5-2012   
4     |    1    | 30-5-2013  
5     |    2    | 30-5-2013  
6     |    3    | 30-5-2014  
7     |    4    | 30-5-2014  
8     |    5    | 30-5-2014
9     |    5    | 30-5-2015 
10    |    5    | 30-5-2016
11    |    1    | 30-5-2010
-------------------------------

我想要做的是只选择paper_update在具有相同user_id的记录之间最大的记录,实际上我想按user_id进行分组,以便最大paper_update。 所以对于这个表,它将返回:

id    | user_id | paper_update
------------------------------
4     |    1    | 30-5-2013  
5     |    2    | 30-5-2013  
6     |    3    | 30-5-2014  
7     |    4    | 30-5-2014  
10    |    5    | 30-5-2016 
-------------------------------

3 个答案:

答案 0 :(得分:7)

这是在laravel中获取groupBy Max Date的最简单最短的方法。使用user_id的分组获取包含最大日期的行。

       $rows = DB::table('papers')
               ->select(DB::raw('id, max(paper_update) as year,user_id'))
               ->groupBy('user_id')
               //->orderBy('paper_update', 'desc')
               ->get();

这个laravel查询将创建一个像这样的

的mysql查询
select id, max(paper_update) as year from `papers` group by `user_id`;

输出将

Array
(
    [0] => stdClass Object
        (
            [id] => 4
            [year] => 30-5-2013 
            [user_id] => 1
        )

    [1] => stdClass Object
        (
            [id] => 5
            [year] => 30-5-2013
            [user_id] => 2
        )

    [2] => stdClass Object
        (
            [id] => 6
            [year] => 30-5-2014
            [user_id] => 3
        )

    [3] => stdClass Object
        (
            [id] => 7
            [year] => 30-5-2014
            [user_id] => 4
        )
    [4] => stdClass Object
        (
            [id] => 10
            [year] => 30-5-2016
            [user_id] => 5
        )
)

答案 1 :(得分:3)

MySQL:

您只能使用Left Join并避免Group By为每个paper_update检索上一个user_id

SELECT t1.*
FROM paper AS t1 LEFT JOIN paper AS t2
ON (t1.user_id = t2.user_id AND t1.paper_update < t2.paper_update)
WHERE t2.paper_update IS NULL;

假设您的表名为paper

SEE DEMO

Laravel Query Builder:

我不是Laravel Query Builder的专家,但你可以试试这个:

$result = DB::table('paper AS t1')
->select('t1.*')
->leftJoin('paper AS t2', function( $join ){
    $join->on( 't1.user_id', '=', 't2.user_id' );
    $join->on( 't1.paper_update', '<', 't2.paper_update' );
})
->whereNull('t2.paper_update')
->get();

答案 2 :(得分:2)

不熟悉laravel的查询构建器,但在普通的Mysql中,您使用具有同一表中最大日期值的自联接

select t.*
from t 
join (
  select `user_id`, max(`paper_update`)`paper_update`
  from t group by `user_id`
  ) t1
using(`user_id`, `paper_update`)

Fiddle Demo