Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine SQL UPDATE STATEMENTS

I am trying to combine these five update statements. I'm sure this is simple but I am new to SQL and can't figure the logic out.

$usqlM1 = "UPDATE tblmaincircles SET mcName= '".$_POST['mcNameM1']."' WHERE mcID='M1';"
$usqlM2 = "UPDATE tblmaincircles SET mcName= '".$_POST['mcNameM2']."' WHERE mcID='M2';";
$usqlM3 = "UPDATE tblmaincircles SET mcName= '".$_POST['mcNameM3']."' WHERE mcID='M3';";
$usqlM4 = "UPDATE tblmaincircles SET mcName= '".$_POST['mcNameM4']."' WHERE mcID='M4';";
$usqlM5 = "UPDATE tblmaincircles SET mcName= '".$_POST['mcNameM5']."' WHERE mcID='M5';";

Any help would be great. Thanks in advance!

like image 971
Craig Howell Avatar asked Feb 08 '23 21:02

Craig Howell


1 Answers

A CASE statement can do this. You can add a where clause so the system doesn't have to evaluate each record and improve performance if MCID is indexed.

UPDATE tblmaincircle set mcname = case when mcid = 'M1' then 'McNameM1'
                                       when mcid = 'M2' then 'McNameM2'
                                       when mcid = 'M3' then 'McNameM3'
                                       when mcid = 'M4' then 'McNameM4'
                                       when mcid = 'M5' then 'McNameM5' end
where mcid in ('M1','M2','M3','M4','M5');
like image 143
xQbert Avatar answered Feb 15 '23 22:02

xQbert