批量更新MySQL,而不是PHP While循环

问题描述 投票:-1回答:1

我正在使用PHP代码更新每个子域在不同日期的星期结束日期。每个子域的日期范围都不同。

我当前的代码使用while循环来更新星期结束日期。这非常慢,我正在寻找优化方法。

这是我当前的代码:


// Loop through and assign week end date to each user activity.
$nextWeek = $startDate;  // initialise while loop condition
while ($nextWeek <= $endDate) {
    $lastWeek = $nextWeek;
    $nextWeek = Carbon::parse($lastWeek)->addWeek(1)->format('Y-m-d');

    // update activity date to week end date
    $query = 'UPDATE r_active_user_activities 
                SET week_end_date = "' . $nextWeek . '"
                WHERE (activity_date > "' . $lastWeek . '" 
                    AND activity_date <= "' . $nextWeek . '"  
                    AND subdomain="' . $subdomain->subdomain . '" );';
    $db->statement($query);
}
php mysql php-carbon bulkupdate
1个回答
0
投票

只需将所有这些更新查询附加到php变量($ query)中,然后在while循环外执行该查询。像这样的东西。

$nextWeek = $startDate;  // initialise while loop condition
$query = '';
while ($nextWeek <= $endDate) {
$lastWeek = $nextWeek;
$nextWeek = Carbon::parse($lastWeek)->addWeek(1)->format('Y-m-d');

// update activity date to week end date
$query .= 'UPDATE r_active_user_activities 
            SET week_end_date = "' . $nextWeek . '"
            WHERE (activity_date > "' . $lastWeek . '" 
                AND activity_date <= "' . $nextWeek . '"  
                AND subdomain="' . $subdomain->subdomain . '" );';
 }
$db->statement($query);
© www.soinside.com 2019 - 2024. All rights reserved.