PostgreSQL - 使用子查询更新列值

问题描述 投票:0回答:2

可能是一个非常简单的解决方案,但我对 PostgreSQL 还很陌生,我需要你帮助好人。我有一个名为 countries 的表,其中包含有关不同国家/地区的信息,后来我添加了一个名为 Three_rivers 的列,该列的类型为 BOOL,默认值为 FALSE。

ALTER TABLE countries ADD COLUMN three_rivers BOOL DEFAULT FALSE
这很好。 我想更新所有在其领土上流经超过 3 条河流的国家的值。我有另一个名为 Rivers 的表,其中包含有关河流的信息,还有一个名为 countries_rivers 的帮助表,它确保原始表 countriesrivers 之间的连接。在这个 countries_rivers 中,我有两列称为 river_id ,即 countries_rivers.river_id = rivers.idcountries_rivers.country_code = countries.country_code。 这是正确选择我想要的结果的查询 - 所有拥有 3 条以上河流的国家: 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

列。最有可能的是 UPDATE countries SET three_rivers=1 WHERE...

提前谢谢您!

postgresql sql-update boolean subquery
2个回答
0
投票

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;



0
投票

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

子查询将获取拥有 3 条河流的国家代码,查询将相应更新。

© www.soinside.com 2019 - 2024. All rights reserved.