Laravel中如何用聚合函数计算总数

本文讲解"Laravel中怎么用聚合函数计算总数",希望能够解决相关问题。

假如有电子邮件订阅服务,希望显示订阅者的详情统计页面如下显示

订阅者总数确认(confirmed)未经证实(unconfirmed)取消(cancelled)拒绝(bounced)
20015050105

出于本文的目的,假设我们有一个subscribers包含以下格式数据的数据库表:

nameemailstatus
小明adam@hotmeteor.comconfirmed
小红taylor@laravel.comunconfirmed
小军jonathan@reinink.cacancelled
小花adam.wathan@gmail.combounced

大部分人的做法:

$total = Subscriber::count();
$confirmed = Subscriber::where('status', 'confirmed')->count();
$unconfirmed = Subscriber::where('status', 'unconfirmed')->count();
$cancelled = Subscriber::where('status', 'cancelled')->count();
$bounced = Subscriber::where('status', 'bounced')->count();

上面这样肯定会产生五条语句,这样做肯定是很不好。所以尝试优化一下,会使用另一个方法解决执行多条语句的问题:

$subscribers = Subscriber::all();
$total = $subscribers->count();
$confirmed = $subscribers->where('status', 'confirmed')->count();
$unconfirmed = $subscribers->where('status', 'unconfirmed')->count();
$cancelled = $subscribers->where('status', 'cancelled')->count();
$bounced = $subscribers->where('status', 'bounced')->count();

上面先获取全部订阅者数据,然后再对这个结果集进行条件统计,使用集合.模型多条数据查询返回Illuminate\Database\Eloquent\Collection。这样的方法,只适合再数据量不大的时候使用,如果我们的应用程序有数千或数百万订阅者,处理的时间会很慢,并且会使用大量内存。

条件聚合

实际上有一种非常简单的方法可以查询计算这些总数。诀窍是将条件放在聚合函数中。下面是一个 SQL 示例:

select
  count(*) as total,
  count(case when status = 'confirmed' then 1 end) as confirmed,
  count(case when status = 'unconfirmed' then 1 end) as unconfirmed,
  count(case when status = 'cancelled' then 1 end) as cancelled,
  count(case when status = 'bounced' then 1 end) as bounced
from subscribers

 total | confirmed | unconfirmed | cancelled | bounced
-------+-----------+-------------+-----------+---------
   200 |       150 |          50 |        30 |      25

————————————————
原文作者:4pmzzzzzzzzzz
转自链接:https://learnku.com/articles/74652
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

以下是在 Laravel 中使用查询构建器编写此查询:

$totals = DB::table('subscribers')
    ->selectRaw('count(*) as total')
    ->selectRaw("count(case when status = 'confirmed' then 1 end) as confirmed")
    ->selectRaw("count(case when status = 'unconfirmed' then 1 end) as unconfirmed")
    ->selectRaw("count(case when status = 'cancelled' then 1 end) as cancelled")
    ->selectRaw("count(case when status = 'bounced' then 1 end) as bounced")
    ->first();

<div>Total: {{ $totals->total }}</div>
<div>Confirmed: {{ $totals->confirmed }}</div>
<div>Unconfirmed: {{ $totals->unconfirmed }}</div>
<div>Cancelled: {{ $totals->cancelled }}</div>
<div>Bounced: {{ $totals->bounced }}</div>

Boolean 列(字段)

表迁移创建 boolean 字段 , model定义属于转换 此处不用model为代码示例,可自行替换为model

如果使用boolean当字段列,将更容易,比如要查询subscribers表中的用户是否为拥有不同的角色权限。假设subscribers表中有is_admin、is_treasurer、is_editor、is_manager、字段

$totals = DB::table('subscribers')
    ->selectRaw('count(*) as total')
    ->selectRaw('count(is_admin or null) as admins')
    ->selectRaw('count(is_treasurer or null) as treasurers')
    ->selectRaw('count(is_editor or null) as editors')
    ->selectRaw('count(is_manager or null) as managers')
    ->first();

这是因为聚合函数count忽略null列。与PHP中false || null返回false不同,在SQL(以及JavaScript)中,它返回null。基本上,如果A可以强制为真,则A || B返回值A;否则,返回B。

这段话如果没理解,就看我下面说明:
使用laravel的boolean列,实际数据表里字段为tinyint,值为0(false)与1(true), 比如
小明的is_admin字段为1(true),count(is_admin or null)可以看作表示为(1 or null),这A为真 返回A,最终sql为count(is_admin)。
反之则是如is_admin字段为0(false),最终sql为count(null),则忽略此列

//PHP  返回 false
var_dump(0 || null) 

//JavaScript 返回 null
console.log(0 || null)

//SQL 返回 null
SELECT (0 or null) as result

关于 "Laravel中怎么用聚合函数计算总数" 就介绍到此。希望多多支持编程宝库

es6如何判断是否在数组里:本文讲解"es6怎么判断是否在数组里",希望能够解决相关问题。判断方法:1、使用includes()函数,可判断数组是否包含一个指定的值,语法“arr.includes(值)”,如果返回true则存在;2、使用f ...