SQL 根据表 2 中的值逐行更新表 1

SQL UPDATE table1 row-by-row based on values in table2

我有两个 table,我想 UPDATE 一个 table 基于另一个 table 的值。 在以下 SO-post 的帮助下,我编写了一个查询:

query = f""" UPDATE table1
             SET goal = 
            (SELECT table2.goal FROM table2                                                                    
             WHERE player = table2.player
                AND opponent = table2.opponent
                AND date = table2.date
                AND competition = table2.competition
                AND score = table2.score """

当我执行查询时,table1 的每一行都会受到 goal 相同值的影响。但是,所需的过程是查询逐行检查是否有匹配的行,如果有,则更新列 goal。我做错了什么?

据我了解,如果 table2 具有相同的值,则此查询只会影响 table1。您要检查是否有任何行相同然后更新目标值吗?

您可以使用 OR 而不是使用 AND。如果任何值相似,此修改将确保查询将通过。

query = f""" UPDATE table1
         SET goal = 
        (SELECT table2.goal FROM table2                                                                    
         WHERE player = table2.player
            OR opponent = table2.opponent
            OR date = table2.date
            OR competition = table2.competition
            OR score = table2.score )"""

您必须将子查询与您要更新的 table 相关联:

UPDATE table1 AS t1
SET goal = (
  SELECT t2.goal 
  FROM table2 AS t2                                                                    
  WHERE t2.player = t1.player
    AND t2.opponent = t1.opponent
    AND t2.date = t1.date
    AND t2.competition = t1.competition
    AND t2.score = t1.score
);

或者:

UPDATE table1 AS t1
SET goal = (
  SELECT t2.goal 
  FROM table2 AS t2                                                                    
  WHERE (t2.player, t2.opponent, t2.date, t2.competition, t2.score) = 
        (t1.player, t1.opponent, t1.date, t1.competition, t1.score)
);

请注意,如果 table1 中的一行与 table2 中的任何行都不匹配,则该列将更新为 null
如果在这种情况下您不想更新该列,还可以使用 COALESCE():

UPDATE table1 AS t1
SET goal = COALESCE((
  SELECT t2.goal 
  FROM table2 AS t2                                                                    
  WHERE (t2.player, t2.opponent, t2.date, t2.competition, t2.score) = 
        (t1.player, t1.opponent, t1.date, t1.competition, t1.score)
), goal);

如果你的 SQLite 版本是 3.33.0+,你可以使用 UPDATE..FROM 语法:

UPDATE table1 AS t1
SET goal = t2.goal 
FROM table2 AS t2                                                                    
WHERE (t2.player, t2.opponent, t2.date, t2.competition, t2.score) = 
      (t1.player, t1.opponent, t1.date, t1.competition, t1.score);