简体   繁体   中英

Query to Update Table using another table as information?

I have two tables, Staff and Wages

Staff Contains

 id,   name,     jobID,   wage
  1   Name1       2        
  2   Name2       4      
  3   Name3       1      
  4   Name4       2      

Wages Contains

 JobID, Wage
   1    1500
   2    800
   3    1600
   4    2000

(There are alot more columns in the actual one I have just took the top 4)

I am missing the wages inside the Staff table, and the wages I need in the staff table are the rates in the Wages table..

So I need a query which would make the Staff table look like:

 id,   name,     jobID,   wage
  1   Name1       2        800
  2   Name2       4        2000
  3   Name3       1        1500
  4   Name4       2        800

An example Query which I tried was:

UPDATE `Staff` 
SET wage = (SELECT wage FROM `Wages`) 
WHERE jobID = (Select jobId FROM `Wages`)

Thanks.

In MySQL ,

UPDATE Staff a
        INNER JOIN Wages b
            ON a.jobID  = b.JobID
SET a.wage = b.wage

In MSSQL ,

UPDATE a
SET a.wage = b.wage
FROM Staff a
        INNER JOIN Wages b
            ON a.jobID  = b.JobID

I would just leave the tables as they are (without the wage column in Staff ), in their normalized state, and run this query anytime I need the full set of (denormalized) data:

SELECT s.id, s.name, s.jobID, w.wage
FROM Staff s
LEFT OUTER JOIN Wages w ON s.jobID = w.jobID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM