Mysql Laravel从一张表中选择价格最低的独特产品
你好,我正在努力以最低的价格买到独特的产品。 我有一个这样的产品表: 我想得到一个包含所有列的产品列表。现在有一些产品有多个供应商,在这种情况下,我想以最低的Mysql Laravel从一张表中选择价格最低的独特产品,mysql,database,laravel,greatest-n-per-group,laravel-query-builder,Mysql,Database,Laravel,Greatest N Per Group,Laravel Query Builder,你好,我正在努力以最低的价格买到独特的产品。 我有一个这样的产品表: 我想得到一个包含所有列的产品列表。现在有一些产品有多个供应商,在这种情况下,我想以最低的成本\价格购买产品 到目前为止我已经试过了 $products = DB::table('products') ->select('identifier') ->selectRaw('MIN(cost_price) as cost_price') ->where('stoc
成本\价格
购买产品
到目前为止我已经试过了
$products = DB::table('products')
->select('identifier')
->selectRaw('MIN(cost_price) as cost_price')
->where('stock', '>', 0)
->groupBy('identifier')
->orderBy('cost_price', 'asc')
->distinct()->get();
此查询返回正确的结果,但我无法在每次添加列时添加更多的列,例如,在“选择我需要添加的列”中以及在“GroupBy”中添加列,然后我仅获取所有产品
怎么做?
感谢您的阅读。您需要
每组最大n个解决此问题的方法
查询
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.*']);
非常感谢您,Ersoy您的解决方案是正确的,非常有用。