【问题标题】:how to get highest 5 values from column?如何从列中获取最高 5 个值?
【发布时间】:2018-01-01 20:38:00
【问题描述】:

我有带有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 

【问题讨论】:

标签: php mysql sql laravel laravel-5


【解决方案1】:

所以如果我在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

【讨论】:

    【解决方案2】:
    $best_sell = DB::table('products')
             ->select('no_of_sell')   
             ->where('products.status','=','1')                       
             ->orderBy('no_of_sell', 'desc')
             ->paginate(4);
    

    【讨论】:

    • 我使用了 desc,但问题是它没有显示合适的。假设 no_of_sell 的值为 7 9 10 12 15 ..如果我想获得 4 个数据。它应该返回 9 10 12 15 但它返回 7 9 12 15
    【解决方案3】:
    $best_sell = DB::table('products')
            ->select() // your selection criteria 
            ->where('products.status','=','1') 
            ->take(5)->get(); 
    

    【讨论】:

    • 只取最高 5 的值。
    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 2023-01-10
    • 2019-12-26
    • 2021-05-06
    • 2022-01-17
    • 2020-10-06
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多