简体   繁体   English

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

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

Dummy data to illustrate my problem:虚拟数据来说明我的问题:

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');

So the data looks like:所以数据看起来像:

Table 1:表格1:

category_id类别ID unit单元 is_valid已验证
1 1 a一个 true真的
2 2 z z true真的

Table 2:表 2:

category_id类别ID unit单元
1 1 a一个
1 1 b b
1 1 c C
2 2 d d
2 2 e e

I want to update the is_valid column in Table 1, if the category_id/unit combination from Table 1 doesn't match any of the rows in Table 2. For example, the first row in Table 1 is valid, since (1, a) is in Table 2. However, the second row in Table 1 is not valid, since (2, z) is not in Table 2.如果表 1 中的 category_id/unit 组合与表 2 中的任何行都不匹配,我想更新表 1 中的 is_valid 列。例如,表 1 中的第一行是有效的,因为 (1, a)在表 2 中。但是,表 1 中的第二行无效,因为 (2, z) 不在表 2 中。

How can I update the column using postgresql?如何使用 postgresql 更新列? I tried a few different where clauses of the form UPDATE table1 SET is_valid = false WHERE... but I cannot get a WHERE clause that works how I want.我尝试了UPDATE table1 SET is_valid = false WHERE...形式的几个不同的 where 子句,但我无法获得一个按我想要的方式工作的 WHERE 子句。

You can just set the value of is_valid the the result of a ` where exists (select ...).您可以将is_valid的值设置为 ` where exists (select ...) 的结果。 See Demo .请参阅演示

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

NOTES:笔记:

  • Advantage: Query correctly sets the is_valid column regardless of the current value and is a vary simple query.优点:查询正确设置is_valid列,而不管当前值如何,并且是一个不同的简单查询。
  • Disadvantage: Query sets the value of is_valid for every row in the table;缺点:查询为表中的每一行设置is_valid的值; even thoes already correctly set.即使已经正确设置。

You need to decide whether the disadvantage out ways the advantage.您需要决定是否将劣势排除在优势之外。 If so then the same basic technique in a much more complicated query:如果是这样,那么在更复杂的查询中使用相同的基本技术:

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