如何用Laravel查询构建器获取参赛国家的计数、去重及总数
使用Laravel查询构建器统计参与赛事的国家相关数据
针对你的需求,我们可以通过Laravel查询构建器结合表关联和聚合函数,轻松实现参与赛事的国家相关统计(包括计数、去重、总数)。先梳理下你的表关联逻辑:country → company → participate_company → competition,我们需要基于这个关联来提取统计数据。
一、统计每个国家的参与明细数据
如果你需要查看每个国家的具体参与情况(比如该国家有多少家公司参与赛事、参与了多少不同的赛事、总参与记录数),可以用下面的查询:
$countryParticipationStats = DB::table('country') // 关联公司表,拿到国家对应的公司 ->join('company', 'country.country_id', '=', 'company.country_id') // 关联参与记录表,拿到公司的赛事参与数据 ->join('participate_company', 'company.company_id', '=', 'participate_company.company_id') // 可选:如果需要关联赛事名称信息,可以加上这个左连接(不需要的话可以删除) ->leftJoin('competition', 'participate_company.competition_id', '=', 'competition.competition_id') ->select([ 'country.country_id', 'country.country_name', // 统计该国家参与赛事的独立公司数量(去重,避免同公司多次参与被重复计数) DB::raw('COUNT(DISTINCT company.company_id) as participating_companies'), // 统计该国家的公司参与过的不同赛事数量(去重) DB::raw('COUNT(DISTINCT participate_company.competition_id) as unique_competitions'), // 统计总参与记录数(包含同公司参与多个赛事的情况) DB::raw('COUNT(participate_company.company_id) as total_participations') ]) // 按国家分组,确保每个国家只返回一条统计结果 ->groupBy('country.country_id', 'country.country_name') ->get();
代码解释:
join操作:把关联的表串联起来,确保我们能获取到从国家到赛事参与的完整链路数据COUNT(DISTINCT ...):用于去重统计,避免同一公司或同一赛事被重复计算groupBy:按国家ID和名称分组,保证每个国家的统计结果单独成一条数据
你可以这样遍历使用统计结果:
foreach ($countryParticipationStats as $stat) { echo "国家:{$stat->country_name} | 参与公司数:{$stat->participating_companies} | 参与赛事数:{$stat->unique_competitions} | 总参与次数:{$stat->total_participations}\n"; }
二、统计整体汇总数据
如果你只需要全局的汇总统计(比如总共有多少个国家参与了赛事、总共有多少家公司参与、总参与记录数),可以用这个更简洁的查询:
$overallStats = DB::table('country') ->join('company', 'country.country_id', '=', 'company.country_id') ->join('participate_company', 'company.company_id', '=', 'participate_company.company_id') ->select([ // 参与赛事的国家总数(去重) DB::raw('COUNT(DISTINCT country.country_id) as total_countries'), // 参与赛事的公司总数(去重) DB::raw('COUNT(DISTINCT company.company_id) as total_companies'), // 所有赛事参与记录的总数 DB::raw('COUNT(participate_company.company_id) as total_participations') ]) ->first();
使用汇总数据的示例:
echo "参与赛事的国家总数:{$overallStats->total_countries}\n"; echo "参与赛事的公司总数:{$overallStats->total_companies}\n"; echo "总参与记录数:{$overallStats->total_participations}\n";
内容的提问来源于stack exchange,提问作者Firdaus
相关产品推荐
相关产品推荐

