更新 x 列

Update x column

如何通过 using/amending 下面提到的脚本

更新 stats table 中的特定列
SELECT
    s.id,
    COUNT(t.val) AS count
FROM stats s
LEFT JOIN
(
    SELECT fir AS val FROM history UNION ALL
    SELECT sec FROM history        UNION ALL
    SELECT thi FROM history        UNION ALL
    SELECT fou FROM history        UNION ALL
    SELECT fif FROM history        UNION ALL
    SELECT six FROM history
) t
    ON s.id = t.val
GROUP BY
    s.id;

根据 Postgres documents 您可以将更新查询与 from 语句一起使用,并在 set

中使用结果
UPDATE stats u_s
SET result = tmp_s.count
FROM (
  SELECT
    s.id,
    COUNT(t.val) AS count
  FROM stats s
  LEFT JOIN
  (
    SELECT fir AS val FROM history UNION ALL
    SELECT sec FROM history        UNION ALL
    SELECT thi FROM history        UNION ALL
    SELECT fou FROM history        UNION ALL
    SELECT fif FROM history        UNION ALL
    SELECT six FROM history
  ) t
    ON s.id = t.val
  GROUP BY
    s.id
) tmp_s
WHERE u_s.id = tmp_s.id;