Laravel 联合查询 count计数去重

这篇博客讨论了在 Laravel 应用中实现待办事件功能时遇到的问题,其中主办人是单一的,而协作人可以是多个。通过创建两个表来存储数据,主表和附表之间形成了一对多的关系。在使用 LeftJoin 查询获取所有数据时,当协作人数量超过一个时,出现了重复数据。作者尝试使用 groupby 进行去重,但 Laravel 的 count 方法只返回了第一条数据的计数,导致计数不准确。为了解决这个问题,作者发现 Laravel 的 distinct 方法可以有效过滤重复数据,并确保计数正确。博客中还展示了如何在 Laravel 中使用 distinct 方法来优化查询。

业务需要做一个待办事件功能,其中主办人是单个,协作人是多个;

然后做了两个表,附表用来存协作人,与主表之间是一对多的关系,

列表显示需要全部数据采用了左连接查询。Left Join 求两个表的交集外加左表剩下的数据。

结果呢,如果协作人是1个的时候没问题,当为多个时,就会出现多条重复数据。

一开始直接采用 group by,这当然可以去重,

不过laravel中封装的count方法 直接取了结果中的第一个数据,

也就是5,实际结果我要的是6,如图:

这样列表显示是没问题,但是计数是不对的。

Laravel中还封装了一个过滤方法

   /**
     * 强制查询仅返回不同的结果。
     *
     * @return $this
     */
    public function distinct()
    {
        $columns = func_get_args();

        if (count($columns) > 0) {
            $this->distinct = is_array($columns[0]) || is_bool($columns[0]) ? $columns[0] : $columns;
        } else {
            $this->distinct = true;
        }

        return $this;
    }

 使用方法:

$total = $conn->distinct('id')->count();

实际上它使用的是Mysql 的 distinct关键字来过滤重复

 这样就过滤掉重复的数据了,计数也就准确了。

public function getRecentlySevenCircle(Request $req) { try{ /*取值*/ $ranchID = $req->ranchID; // 1. 获取所有有数据的日期(最多7天,按日期倒序) $existingDates = DB::table('trace_archives_circle') ->select(DB::raw("DISTINCT DATE(circleTime) as date")) ->where('ranchID', $ranchID) ->where('del', '0') ->orderBy('date', 'desc') ->limit(7) ->pluck('date'); // 如果没有数据,返回空数组 if ($existingDates->isEmpty()) { return response()->json(['code' => 403, 'message' => "近七日出圈数据", 'list' => $existingDates]); } // 2. 确定日期范围 $dateRange = collect(); if ($existingDates->count() >= 7) { // 情况1:已经有7天或更多数据,直接使用最近的7天 foreach ($existingDates->take(7) as $date) { $carbonDate = Carbon::parse($date); $dateRange->put($date, [ 'formatted_date' => $carbonDate->format('m-d'), 'count' => 0 ]); } } else { // 情况2:不足7天,从最早日期往前推算补足7天 $earliestDate = Carbon::parse($existingDates->last()); $daysNeeded = 7 - $existingDates->count(); // 先添加已有日期 foreach ($existingDates as $date) { $carbonDate = Carbon::parse($date); $dateRange->put($date, [ 'formatted_date' => $carbonDate->format('m-d'), 'count' => 0 ]); } // 再往前补足缺少的天数 for ($i = 1; $i <= $daysNeeded; $i++) { $date = $earliestDate->copy()->subDays($i); $dateRange->put($date->format('Y-m-d'), [ 'formatted_date' => $date->format('m-d'), 'count' => 0 ]); } } // 3. 查询这些日期的统计数据 $stats = DB::table('trace_archives_circle') ->select( DB::raw("DATE(circleTime) as date"), DB::raw("DATE_FORMAT(circleTime, '%m-%d') as formatted_date"), DB::raw('COUNT(DISTINCT earID) as count') ) ->where('ranchID', $ranchID) ->whereIn(DB::raw('DATE(circleTime)'), $dateRange->keys()) ->where('del', '0') ->groupBy('date', 'formatted_date') ->get() ->keyBy(function ($item) { return Carbon::parse($item->date)->format('Y-m-d'); }); // 4. 合并数据(有数据的覆盖默认值) $mergedData = $dateRange->map(function ($default, $ymd) use ($stats) { return $stats->has($ymd) ? (array)$stats[$ymd] : $default; }); // 5. 格式化返回数据(按日期升序排列) $sortedData = $mergedData->sortKeys(); // 改为sortKeys()实现升序排列 $result = [ 'x' => $sortedData->pluck('formatted_date')->values()->toArray(), 'y1' => $sortedData->pluck('count')->values()->toArray() ]; return response()->json(['code' => 200, 'message' => "近七日出圈数据", 'list' => $result]); }catch(\Exception $e) { return response()->json(['code' => 403, 'message' => $e->getMessage()]); } }逐句解释这段代码
07-13
我有两个表,分别是: //用户信息表 DROP TABLE IF EXISTS `v2_user`; CREATE TABLE `v2_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(64) NOT NULL, `password` varchar(64) NOT NULL, `t` int(11) NOT NULL DEFAULT '0' COMMENT '最后在线时间', `last_login_at` int(11) DEFAULT NULL COMMENT '最后登录时间', `created_at` int(11) NOT NULL, `updated_at` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; //登录记录表(如果用户user_id登录过,就会有一条记录) DROP TABLE IF EXISTS `v2_stat_user`; CREATE TABLE `v2_stat_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `record_at` int(11) NOT NULL, `created_at` int(11) NOT NULL, `updated_at` int(11) NOT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 和两个文件,分别是: //user.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'v2_user'; protected $dateFormat = 'U'; protected $guarded = ['id']; protected $casts = [ 'created_at' => 'timestamp', 'updated_at' => 'timestamp' ]; } //StatUser.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class StatUser extends Model { protected $table = 'v2_stat_user'; protected $dateFormat = 'U'; protected $guarded = ['id']; protected $casts = [ 'created_at' => 'timestamp', 'updated_at' => 'timestamp' ]; } 我原本使用的如下php代码统计的“次日留存”和“七日留存”: $created_data = User::whereNotNull('created_at') ->where('created_at', '>', $limitTime) ->select( DB::raw('DATE(FROM_UNIXTIME(created_at + 28800)) as created_date'), DB::raw('COUNT(*) as created_count'), // 次日留存:创建后第二天有登录行为的用户数 DB::raw('SUM(CASE WHEN t IS NOT NULL AND t >= created_at + 86400 AND t < created_at + 172800 THEN 1 ELSE 0 END) as next_day_retention'), // 7日留存:创建后第7天有登录行为的用户数 DB::raw('SUM(CASE WHEN t IS NOT NULL AND t >= created_at + 604800 AND t < created_at + 691200 THEN 1 ELSE 0 END) as seven_day_retention') ) ->groupBy('created_date') ->orderBy('created_date', 'DESC') ->get(); 我发现通过“最后在线时间”判断并不准确,原因是“最后在线时间”会变。 现在打算通过“登录记录表”来判断,代码该怎么写,user.php和StatUser.php该怎么修改?
最新发布
10-29
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JSON_L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值