繁体   English   中英

Postgresql 根据另一个表中的一组值更新列

[英]Postgresql update column based on set of values from another table

虚拟数据来说明我的问题:

create table table1 (category_id int,unit varchar,is_valid bool);

insert into table1 (category_id, unit, is_valid)
VALUES (1, 'a', true), (2, 'z', true);
create table table2 (category_id int,unit varchar);

insert into table2 (category_id, unit)
values(1, 'a'),(1, 'b'),(1, 'c'),(2, 'd'),(2, 'e');

所以数据看起来像:

表格1:

类别ID 单元 已验证
1 一个 真的
2 z 真的

表 2:

类别ID 单元
1 一个
1 b
1 C
2 d
2 e

如果表 1 中的 category_id/unit 组合与表 2 中的任何行都不匹配,我想更新表 1 中的 is_valid 列。例如,表 1 中的第一行是有效的,因为 (1, a)在表 2 中。但是,表 1 中的第二行无效,因为 (2, z) 不在表 2 中。

如何使用 postgresql 更新列? 我尝试了UPDATE table1 SET is_valid = false WHERE...形式的几个不同的 where 子句,但我无法获得一个按我想要的方式工作的 WHERE 子句。

您可以将is_valid的值设置为 ` where exists (select ...) 的结果。 请参阅演示

update table1 t1
   set is_valid = exists (select null 
                            from table2 t2 
                           where (t2.category_id, t2.unit) = (t1.category_id, t1.unit) 
                         ); 

笔记:

  • 优点:查询正确设置is_valid列,而不管当前值如何,并且是一个不同的简单查询。
  • 缺点:查询为表中的每一行设置is_valid的值; 即使已经正确设置。

您需要决定是否将劣势排除在优势之外。 如果是这样,那么在更复杂的查询中使用相同的基本技术:

with to_valid (category_id, unit, is_valid) as 
     (select category_id
           , unit
           , exists (select null 
                       from table2 t2 
                      where (t2.category_id, t2.unit) = (t1.category_id, t1.unit) 
                    ) 
       from table1 t1
     ) 
update table1  tu
   set is_valid = to_valid.is_valid 
  from to_valid 
 where (tu.category_id, tu.unit) = (to_valid.category_id, to_valid.unit) 
   and tu.is_valid is distinct from to_valid.is_valid;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM