更新与另一个 table 的最大匹配项的列

Updating a column with maximum matches from another table

我有两个 table 假设 A 和 B,我想更新 table A 中的 Status 列,最大匹配来自 table B 中的 Scores 列比较两个 table 的 'Topics'。

我正在使用此处显示的脚本,但它需要很长时间,所以如果有人可以提供替代方案/更好更快的方案,我将不胜感激option/script

UPDATE tableA 
SET status = (SELECT max(scores) 
                        FROM tableB
                        WHERE tableB.topics = tableA.topics)

尝试为涉及的每个列创建适当的索引,您应该没问题,例如:

CREATE INDEX idx_tableb_topics_scores ON tableb (topics,scores);

您的查询的另一种方法是应用聚合函数 max(),只需执行一次,但我怀疑它会加快速度:

UPDATE tablea a SET status = j.max_scores
FROM (SELECT a.topics,max(b.scores) AS max_scores 
      FROM tablea a
      JOIN tableb b ON a.topics = b.topics
      GROUP BY a.topics) j
WHERE a.topics = j.topics;

对于此查询:

UPDATE tableA 
    SET status = (SELECT max(scores) 
                  FROM tableB
                  WHERE tableB.topics = tableA.topics
                 );

您唯一需要的索引是 tableB(topics, scores)

如果你愿意,你可以将其重写为聚合,如下所示:

UPDATE tableA
    SET status = b.max_scores
    FROM (SELECT b.topic, MAX(scores) as max_scores
          FROM tableB b
          GROUP BY b.topic
         ) b
    WHERE b.topic = a.topic;

请注意,这与您的查询略有不同。如果 A 中的主题不在 B 中,则不会更新这些行。不知道可不可以。

如果 A 中的许多行具有相同的 topic,则预聚合可能比相关子查询快得多。