mysql update table field from another table

Viewed 36

i have these set of tables

CREATE TABLE `staff` (
  `id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `uid` varchar(128) NOT NULL,
  `name` varchar(128) NOT NULL,
  `deptname` varchar(128) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `staff` (`id`, `uid`, `name`, `deptname`) VALUES
(1,'A100','John','Finance'),
(2,'A101','Joana','ICT'),
(3,'A103','Darrel','Maintenance'),
(4,'A104','Smith','HR');


CREATE TABLE `department` (
  `id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
  `deptname` varchar(128) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `department` (`id`, `deptid`, `deptname`) VALUES
(1,'100','ICT'),
(2,'200','Finance'),
(8,'300','HR'),
(11,'400','Maintenance'),
(12,'500','Backup');

CREATE TABLE `new_staff` (
  `id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `uid` varchar(128) NOT NULL,
  `name` varchar(128) NOT NULL,
  `deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `new_staff` (`id`, `uid`, `name`, `deptid`) VALUES
(1,'A100','John','600'),
(2,'A103','Darrel','400'),
(3,'A104','Smith','300'),
(4,'A101','Joana','500'),
(5,'A105','Fran','800');

i would like to update the deptid field in the new_staff table to have the correct deptid as listed in the department table

in the new_staff table deptid are currently wrong for John and Joana

this is what i tried so far

// list all deptid exists
$result=$mysqli->query("SELECT deptid FROM department");
    while ($rows=mysqli_fetch_array($result))
{$deptid[]=$rows['deptid'];}
$deptidarray = implode(', ', $deptid);

echo "<br>";

//echo "$deptidarray<br>";

$query=$mysqli->query("SELECT deptid from new_staff WHERE deptid not in ($deptidarray)");
echo "<br>";
$rowtotal = mysqli_num_rows($query);
if($rowtotal>0){
    while ($row=mysqli_fetch_array($query))
{
    $deptid=$row['deptid'];
//  echo "$deptid,";

//$query=$mysqli->query("UPDATE new_staff set deptid='$deptid' WHERE ");

}
}
else
{
    // not found
}

is this possible to do entirely in mysql?

1 Answers
UPDATE new_staff AS ns
JOIN staff AS s ON 
     ns.uid = s.uid             // 1. Get same users from 2 tables
JOIN department AS d ON
     s.deptname = d.deptname    // 2. Get department
SET ns.deptid = d.deptid        // 4. Update correct department id
WHERE ns.deptid != d.deptid;    // 3. Get users where department is incorrect

Run SELECT query first before updating to verify the updates.

SELECT ns.*, d.deptid AS new_dept_id
FROM new_staff AS ns
JOIN staff AS s ON 
     ns.uid = s.uid
JOIN department AS d ON
     s.deptname = d.deptname
WHERE ns.deptid != d.deptid;
Related