首页 > 解决方案 > Laravel 从一张表中选择价格最低的独特产品

问题描述

美好的一天,我正在努力以最低的价格获得独特的产品。我有一个这样的产品表: 在此处输入图像描述

我想获得所有列的产品列表。现在有一些产品有多个供应商,在这种情况下我想抢最低的产品cost_price

到目前为止,我已经尝试过了

$products = DB::table('products')
        ->select('identifier')
        ->selectRaw('MIN(cost_price) as cost_price')
        ->where('stock', '>', 0)
        ->groupBy('identifier')
        ->orderBy('cost_price', 'asc')
        ->distinct()->get();

这个查询返回了正确的结果,但是每次我添加一列时我都不能添加更多列,例如stock在选择中我需要在 GroupBy 中添加,然后我只是得到所有产品。

怎么做? 感谢您的阅读。

标签: mysqldatabaselaravelgreatest-n-per-grouplaravel-query-builder

解决方案


您需要greatest-n-per-group解决此问题的解决方案/方法。

查询;

SELECT products.*
FROM products
         INNER JOIN (SELECT identifier, MIN(cost_price) AS minPrice
                     FROM products
                     WHERE stock > 0
                     GROUP BY identifier) AS sub
             ON sub.minPrice = products.cost_price and sub.identifier = products.identifier;

查询生成器版本;

$sub = DB::table('products')
    ->where('stock', '>', DB::raw(0))
    ->groupBy('identifier')
    ->select('identifier', DB::raw('min(cost_price) as minPrice'));

return DB::table('products')
    ->join(DB::raw('(' . $sub->toSql() . ') as sub'), function ($join) {
        $join->on('sub.minPrice', '=', 'products.cost_price');
        $join->on('sub.identifier', '=', 'products.identifier');
    })
    ->get(['products.*']);

推荐阅读