如何从列中获取最高5个值?

时间:2017-07-26 13:26:11

标签: php mysql sql laravel laravel-5

我的产品表包含nameno_of_sell列。 我想根据产品表中的no_of_sell列获得最高的5个销售产品。 我如何将它与查询构建器一起使用?

  $propular_products =  DB::table('users')
            ->join('products','products.auth_id','users.id')
            ->select('products.*')   
            ->orderBy('products.no_of_sell', 'desc')              
            ->where('products.status','=','1') 
            ->paginate(5);

假设products表:

name no_of_sell
 x     6
 y     9
 z     10
 t     23
 u     3
 h     11
 r      5

我想找到

products list of 5 max no_of_sell ie, x y z t h 

3 个答案:

答案 0 :(得分:0)

因此,如果我在列no_of_sell中正确理解它是一个int。我应该写如下:

$best_sell = DB::table('products')
             ->orderBy('no_of_sell', 'desc')
             ->limit(5)
             ->where('products.status','=','1') 
             ->paginate(4)
             ->get(); 

https://laravel.com/docs/5.4/queries#retrieving-results https://laravel.com/docs/5.4/queries#ordering-grouping-limit-and-offset

答案 1 :(得分:0)

$best_sell = DB::table('products')
         ->select('no_of_sell')   
         ->where('products.status','=','1')                       
         ->orderBy('no_of_sell', 'desc')
         ->paginate(4);

答案 2 :(得分:0)

$best_sell = DB::table('products')
        ->select() // your selection criteria 
        ->where('products.status','=','1') 
        ->take(5)->get();