Laravel 一条 SQL 如何 count 多个字段,Laravel 一条 sql 查询每个分类的数量
在我们做统计的时候,我们常常需要计算各种分类的条数,有的人就迷茫了,我要计算10个分类,就要写10条SQL?那这也太麻烦了吧?群里一个朋友就是这么写的,我们来看一下他的SQL
一. 错误案例
这样写4条SQL,如果我是100个分类,我的天,你得疯掉吧?
二. 解决办法
那行,我们来解决一下,这个时候我选择用一下原始表达式:
$users = DB::table('notice')
// notice_sort是为了看分类,可不要
->select(DB::raw('count(*) as user_count, notice_sort'))
->groupBy('notice_sort')
->get();
dump($users);
然后我们看一下输出的结果
我们再来看一下SQL,问题解决了:
select count(*) as user_count, notice_sort from `notice` group by `notice_sort`
转载请注明 :一沙网络原文出处:http://bbs.earnp.com/article/381
问题交流群 :562864481
本作品采用《CC 协议》,转载必须注明作者和本文链接
说白了,就是基本 sql 的 group 用法:laughing:
这样用group有个小毛病,没有某一类型的数据时这个类型的统计结果不会显示,不知道在数据库层面有办法解决没有
求用户订单的各个状态的总条数
$data = Order::where('member_id', $request->member_id)->field(
"sum(case when evaluation_state = 1 then 1 else 0 end) as order_noeval_count,
sum(case when order_state = 2 then 1 else 0 end) as order_nopay_count,
sum(case when order_state = 3 then 1 else 0 end) as order_noreceipt_count,
sum(case when order_state = 4 then 1 else 0 end) as order_noship_count,
sum(case when refund_state =5 then 1 else 0 end) as order_refund_count "
)->find();