Query Optimization, changing the queries in the loop into a single processing query



PHP Snippet 1:

update applicants a
join applicant_apps aa on aa.applicant_id = a.id
set a.created_at = aa.created_at
where a.created_at = 0;

PHP Snippet 2:

$db::table('applicants as a')
     ->where( $db::raw("`a`.`created_at`"), 0)
     ->join('applicant_apps as aa', 'aa.applicant_id', '=', 'a.id')
     ->update([ 'a.created_at' => $db::raw("`aa`.`created_at`") ])
     ;

PHP Snippet 3:

$applicantIds = \DB::select('id')->from( 'applicants' )->where( 'created_at', 0 )->execute()->as_array('id');

$applicantApps = \DB::select( 'applicant_id', 'created_at' )->from( 'applicant_apps' )->where( 'applicant_id', 'in', array_keys($applicantIds))->execute();

$statement = '';
foreach ($applicantApps as $applicantApp) 
{
    $applicantId = $applicantApp['applicant_id'];
    $applicantCreatedAt = $applicantApp['created_at'];
    $statement .= "update applicants set created_at='$applicantCreatedAt' where id = '$applicantId';";
}

\DB::query($statement)->execute();