使用内部联接更新字段

时间:2014-01-22 15:23:38

标签: asp.net sql

我正在尝试使用INNER JOIN从另一个表更新表中的字段。这是代码:

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

这不起作用我不知道为什么!任何的想法?当我运行查询时,我收到以下错误

There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token        in error = INNER ]

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

并非所有数据库都支持join update语法。当他们这样做时,语法不同。这是一种使用标准SQL在没有显式join的情况下进行查询的方法:

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
             );

只有在可能有多个匹配行时才需要max()

只有在where打算进行过滤和匹配时才需要join

答案 2 :(得分:0)

您使用Inner join子句中的Updated表

例如:

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