关于sql两种计算方式,哪种好呢?

两种在后端计算好佣金以后返回前端的方式,哪种好呢?尽量不要在sql里计算吗?

第一种:

$allList = Merchant::where('ident_status', 10)
                    ->select('id','user_id','store_pic','company_name')
                    ->has('merchant_goods')
                    ->with(['merchant_goods' => function($query) use ($user_prcent) {
                        $query->select('id', 'merchant_id', 'merchant_pics', 'merchant_goods_title', 'merchant_goods_sell_price', 'merchant_goods_total_price', 'fake_sell_count', 'merchant_goods_prcent')
                              ->addSelect(\DB::raw('(merchant_goods_sell_price * merchant_goods_prcent * '.$user_prcent.') as user_share_income'));
                    }])
                    ->orderBy('created_at', 'desc')
                    ->paginate(4);

第二种

$allListSql = Merchant::where('ident_status', 10)
    ->select('id', 'user_id', 'store_pic', 'company_name')
    ->has('merchant_goods')
 ->with('merchant_goods:id,merchant_id,merchant_pics,merchant_goods_title,merchant_goods_sell_price,merchant_goods_total_price,fake_sell_count,merchant_goods_prcent')
    ->orderBy('created_at', 'desc');

$allList = $allListSql->paginate(4);

// 遍历查询结果进行数据处理
foreach ($allList as $item) {
    $item->merchant_goods->map(function ($goods) {
        $goods->setAttribute('merchant_goods_total_price', $goods->merchant_goods_sell_price * $goods->merchant_goods_prcent);
        return $goods;
    });
}

// 组装结果
$allList->transform(function ($item) {
    $item->setAttribute('merchant_goods', $item->merchant_goods);
    return $item;
});
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 11

谢谢

1年前 评论
wongvio (楼主) 1年前

我不会在sql中计算

1年前 评论
wongvio (楼主) 1年前

在代码中计算的话,可以考虑使用访问器吧。

1年前 评论

如果后台数据库支持函数或过程,最好是在数据库端做函数进行统计,前端直接调用结果是最快最节省资源的; 不采用这种方式的话,方案一比方案2好,因为查询是采用的数据库计算,要比PHP进行计算的话消耗的资源和时间少

1年前 评论

通常来说,我们应该尽可能避免在 MySQL 中进行复杂的运算或逻辑操作,因为这可能会导致查询性能下降。相反,我们可以使用 PHP 中的数学函数和逻辑函数来完成这些操作。

然而,如果你需要对两个列进行简单的数值运算(例如相乘),MySQL 中的计算函数仍然是一个不错的选择,因为这些操作可以直接在查询中完成,避免了数据在 PHP 和 MySQL 之间的频繁传输。当然,如果你需要进行更复杂的计算,建议使用 PHP 中的数学函数或编写自定义函数。同时,对于大型数据集,可以考虑对查询进行优化,使用索引和分区等技术来提高查询性能。 ChatGPT 的回答~

1年前 评论

我肯定用第2种方法,比较万能。

1年前 评论

又不是在 where 里计算,怕什么。

1年前 评论

建议不要在sql里计算 数据越多这样用性能越不好 建议使用第二种

11个月前 评论

数量小,怎么都可以。 1、从数据优化上来看,最好少用数据库来计算,数据库,数据库,顾名思义,它的本质就是存储数据 2、数据如果数据量大,且计算复杂,耗费的时间长,建议使用冗余字段

11个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!