也许只是因为它真的很晚了,这可能是一件非常简单的事情,但我的查询存在问题:
npm install -g update-notifier,
我的问题是$lead = Lead::findOrFail($id);
$recipients = Recipient::with('segment')
->select('recipients.*',
DB::raw('coalesce(rulesets.name, "Accept any...") as ruleset_name'),
DB::raw('coalesce(sum(recipient_leads.leads_left), 0) as leads_left'),
DB::raw('round(min('.((configuration('location_distance_unit') == 'km') ? '6371' : '3959').' * acos(cos(radians('.$lead->latitude.')) * cos(radians(recipient_locations.latitude)) * cos(radians(recipient_locations.longitude) - radians('.$lead->longitude.')) + sin(radians('.$lead->latitude.')) * sin(radians(recipient_locations.latitude))))) as distance'))
->leftJoin('rulesets', 'rulesets.id', '=', 'recipients.ruleset_id')
->leftJoin('recipient_leads', 'recipient_leads.recipient_id', '=', 'recipients.id')
->leftJoin('recipient_locations', 'recipient_locations.recipient_id', '=', 'recipients.id')
->where('recipients.segment_id', $lead->segment_id)
->where(function ($query) use ($lead) {
$query->whereIn('recipients.ruleset_id', $lead->rulesetIds())->orWhereNull('recipients.ruleset_id');
})
->whereRaw('distance <= recipient_locations.distance')
->where('recipients.active', true)
->where('leads_left', '>', 0)
->groupBy('recipients.id');
总和似乎乘以leads_left
的数量。我已尝试将recipient_locations
和recipient_locations.recipient_id
添加到我的groupBy中,但它没有效果。
为什么会发生这种情况,我该如何解决?
编辑:这是原始查询:
recipient_leads.recipient_id
答案 0 :(得分:0)
所以我不会尝试重写整个查询,但问题是当你使用多个左连接时,左边的匹配行会在右边重复(这就是为什么你的总和是错)。
如果您在加入之前计算sum
,它应该按照您想要的方式工作。
实际上这是以前的答案,很好地解释了它: