简体   繁体   中英

Update field using inner join

I am trying to update a field in a table from another table using INNER JOIN. Here is the code:

UPDATE TestResults  
INNER JOIN Distractors 
ON TestResults.DistractorID = Distractors.ID 
SET    TestResults.DistractorValue = Distractors.DistractorValue

This does not work I don't know why! Any idea? When I run the query I get the following error

There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token        in error = INNER ]
UPDATE TestResults
SET TestResults.DistractorValue = Distractors.DistractorValue
FROM TestResults
INNER JOIN Distractors 
ON TestResults.DistractorID = Distractors.ID

Not all databases support join syntax with update . And when they do, the syntax differs. Here is a way to do your query without an explicit join using standard SQL:

UPDATE TestResults  
    set DistractorValue = (select max(d.DistractorValue)
                           from Distractors d
                           where TestResults.DistractorValue = d.DistractorValue
                          )
where exists (select 1
              from Distractors d
              where TestResults.DistractorValue = d.DistractorValue
             );

The max() is only needed if there could be more than one matching row.

The where is only needed if the join is intended to do filtering as well as matching.

You use the Updated table in the Inner join clause

ex:

  UPDATE TestResults  
    SET    TestResults.DistractorValue = Distractors.DistractorValue
    FROM TestResults INNER JOIN Distractors 
    ON TestResults.DistractorID = Distractors.ID 

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