PostgreSQL -使用子查询更新列值

djmepvbi  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(120)

countries包含有关不同国家和另一列的信息:

ALTER TABLE countries
ADD COLUMN three_rivers BOOL DEFAULT FALSE

我想更新在其境内有3条以上河流的国家的值。
rivers包含有关河流的信息,表countries_rivers确保原始表之间的连接。它有两列,river_id,其中countries_rivers.river_idrivers.idcountries_rivers.country_codecountries.country_code
这会选择我想要的结果:

SELECT country_code,
    COUNT(country_code) AS counter
FROM countries_rivers
GROUP BY country_code
HAVING COUNT(country_code)>3
ORDER BY counter DESC

如何使用子查询将countries.three_rivers更新为counter
比如UPDATE countries SET three_rivers=1 WHERE ...

mgdq6dx1

mgdq6dx11#

可以使用子查询进行更新。

WITH RiverCounts AS (
  SELECT country_code, COUNT(country_code) AS counter
  FROM countries_rivers
  GROUP BY country_code
  HAVING COUNT(country_code) > 3
)
UPDATE countries c
SET three_rivers = TRUE
FROM RiverCounts rc
WHERE c.country_code = rc.country_code;
rekjcdws

rekjcdws2#

以下查询应该可以工作:

UPDATE countries
SET three_rivers = TRUE
WHERE country_code IN (
    SELECT country_code
    FROM countries_rivers
    GROUP BY country_code
    HAVING COUNT(*) > 3
);

该子查询将获得拥有3条河流的国家的代码,并且查询将相应地更新。

相关问题