You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL:如何通过子查询更新countries表的three_rivers字段

实现PostgreSQL更新操作:标记拥有3条以上河流的国家

方式一:使用IN子查询

直接基于你提供的筛选逻辑,提取符合条件的country_code作为子查询,匹配countries表完成更新:

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

注:子查询无需保留ORDER BY和counter字段,仅需匹配国家编码即可。

方式二:使用EXISTS子查询(大数据量场景推荐)

如果数据库数据量较大,EXISTS子查询的执行效率通常更高——它找到匹配项后会立即停止检索:

UPDATE countries c
SET three_rivers = TRUE
WHERE EXISTS (
    SELECT 1
    FROM countries_rivers cr
    WHERE cr.country_code = c.country_code
    GROUP BY cr.country_code
    HAVING COUNT(cr.country_code) > 3
);

可选:重置不符合条件的国家字段

若需要确保所有不满足"拥有3条以上河流"的国家,其three_rivers字段都为默认的FALSE,可执行反向更新:

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

内容的提问来源于stack exchange,提问作者ddoch003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 18:22:06