Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating multiple rows in MySQL without a loop

I'm trying to write up an email notification system for a job recruitment site I made and am currently looking at grouping a certain amount of jobs together before sending an email to the candidate

I have a table which I've called candidate_to_job which contains the candidate_id, job_id and an "emailed" boolean

What I'm struggling with is updating that table when a new job is posted and emails are sent out. So far when a new job is posted I run the following:

SELECT     c2j.candidate_id, c2j.job_id, j.title 
FROM       " . DB_PREFIX . "candidate_to_job c2j 
LEFT JOIN  " . DB_PREFIX . "job j 
       ON  (j.job_id = c2j.job_id) 
WHERE      c2j.emailed = 0

Then through PHP I group them all together so I have an array looking something like this:

$candidates = array(
    1 => array(1,2,3),
    2 => array(1,3),
    3 => array(4,5,6)
);

With the array key being the candidate ID and the value an array of job IDs

What I want to do using that array - after the emails have been sent - is update the candidate_to_job table setting emailed to true, e.g candidate_id 1 would have emailed set to true for job_ids 1, 2 and 3

Is there a way I can do this in one query? I've looked at WHEN CASE statements but I don't think that applies in this case? I really don't want to run multiple queries per candidate because there could potentially be thousands!

like image 796
Andy Avatar asked Feb 22 '26 06:02

Andy


1 Answers

You can run one UPDATE query per group provided that the group can share the same WHERE criteria and the same update values.

UPDATE tbl SET value = TRUE WHERE id IN(1,2,3,4,5,6);
UPDATE tbl SET value = FALSE WHERE id IN(7,8,9,10,11);

Or you can use the WHEN clause or even some IF clauses provided that the criteria are simple enough.

UPDATE tbl SET value = IF(id = 1) WHERE id IN(1,2);
UPDATE tbl
    SET value = CASE
                    WHEN id IN (1,2,3,4,5,6) THEN TRUE
                    WHEN id IN (7,8,9,10,11) THEN FALSE
                    ELSE value
                END
    WHERE id IN (1,2,3,4,5,6,7,8,9,10,11);

Having possibly thousands of WHEN cases, may be a hassle to build/change, I'd go with the first option:

Flip the old key=>value array and keep all ids connected to a value:

foreach($list AS $id => $value) {
    $list2[$value][] = $id;
}

Iterate through the value=>keys array and build UPDATE queries that can bulk update the value for all keys at once.

like image 73
Mihai Stancu Avatar answered Feb 24 '26 21:02

Mihai Stancu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!