1 ) ORDER BY custom_no;"; $res = DB::connection('vd_old')->select($sql); $array = []; foreach ($res as &$item) { $item = (array)$item; } $res = array_groupBy($res, 'custom_no'); foreach ($res as $custom_no => $group) { $group = array_groupBy($group, 'valid_start_time'); foreach ($group as $arr) { if (count($arr) < 2) { continue; } $item = $arr[0]; $rows = DB::connection('vd_old')->table('ckb_custom_handle_log') ->where('company', $item['company']) ->where('content', $item['content']) ->whereNotIn('custom_no', array_pluck($array, 'custom_no')) ->groupBy('custom_no') ->havingRaw(DB::raw("MAX(valid_end_time) < {$item['valid_start_time']}")) ->orderBy('valid_end_time', 'desc') ->limit(count($arr) - 1) ->get(); foreach ($arr as $key => $item) { if ($key === 0) { continue; } if (!$rows[$key - 1]) { throw new \Exception('未找到卡 #:'. $item['custom_no']); } echo $key . ',' . $item['custom_no'] . ',' . date('Y-m-d H:i:s', $item['valid_start_time']) . ',' . $rows[$key - 1]->custom_no . PHP_EOL; $array[] = [ 'id' => $item['id'], 'custom_no' => $rows[$key - 1]->custom_no, ]; } } } DB::transaction(function () use ($array) { foreach ($array as $item) { DB::connection('vd_old')->table('ckb_custom_handle_log')->where('id', $item['id'])->update(['custom_no' => $item['custom_no']]); } }); dd($array);