mysql - 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 中添加,然后我只是得到所有产品。
怎么做? 感谢您的阅读。
解决方案
您需要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.*']);
推荐阅读
- android - 如何从本地数据库导出/导入数据?
- swift - Xcode Storyboard 无法显示(渲染)ViewControllers(代理崩溃)
- mysql - 为不同的用户选择最大和最小日期时间
- python - 如何在特定路径中为 vscode 使用 python 语言服务器?
- python - 由于 AttributeError,无法区分 3D 中的样条线
- java - 如何使用 FitNesse 测试 Java 类
- html - 我无法让 Rainbow Text 工作。我在这里做错了吗?
- python - 使用 pyfmi 库在 python 中加载 fmu 时出错
- excel - 为什么现在删除重复项会引发错误?
- c# - 在独木舟配置模拟中自动生成节点