Mysql 将SQL中的列值相乘,然后将所有值相加-Laravel 4
我有以下代码:Mysql 将SQL中的列值相乘,然后将所有值相加-Laravel 4,mysql,laravel,sum,multiplication,Mysql,Laravel,Sum,Multiplication,我有以下代码: DB::table('product_list')->select(DB::raw('(value*quantity) as total'))->get(); 这是我的数据库: product = id,quantity,value,color 我希望它们都像这样添加: 1|10|500|blue 2|20|250|red total for each = value*quantity total = 10000 但它给了我: array(2) { [0]=&g
DB::table('product_list')->select(DB::raw('(value*quantity) as total'))->get();
这是我的数据库:
product = id,quantity,value,color
我希望它们都像这样添加:
1|10|500|blue
2|20|250|red
total for each = value*quantity
total = 10000
但它给了我:
array(2) { [0]=> object(stdClass)#266 (1) { ["total"]=> int(5000) } [1]=> object(stdClass)#263 (1) { ["total"]=> int(5000) } }
求和的唯一方法是在PHP中运行foreach循环,但我需要直接从数据库中执行。但是肯定有另一种方法,不是吗?使用SQL
SUM
函数:
$total = DB::table('product_list')
->selectRaw('SUM(value * quantity) as total')
->pluck('total');
嘿,
selectRaw
这是一个非常好的查询,这是我的最后一个查询:DB::table('product_list')->selectRaw('SUM(value*quantity)as total')->pull('total')
,直接获取总值,谢谢。