【问题标题】:postgres - update a row based on other rowspostgres - 根据其他行更新一行
【发布时间】:2016-09-06 21:06:00
【问题描述】:

我想知道,如何根据其他行的值更新某些列为空的行。

我想用下面两行中的值更新第一行的列(user_name、database_name、connection_from)。 session_id 相同。

谢谢。

【问题讨论】:

  • 这方面的关键部分是了解您尝试收集的数据,而不是更新本身。如果您知道如何选择您需要的数据,那么更新很简单。在不知道表定义的详细信息(尤其是主键)的情况下,我无法更具体。顺便说一句,您应该考虑将连接信息存储为 connection_ip inet 和 connection_port int; inet 类型为您提供了一些强大的运算符。

标签: sql postgresql sql-update


【解决方案1】:

关于如何选择要更新的值,您的问题相当模糊。假设您正在查看基于 session_id 的数据,并且任何非 NULL 值都适用于这三列:

update t
    set user_name = coalesce(t.user_name, tt.user_name),
        database_name = coalesce(t.database_name, tt.database_name),
        connection_from = coalesce(t.connection_from, tt.connection_from)
    from (select session_id, max(user_name) as user_name,
                 max(database_name) as database_name,
                 max(connection_from) as connection_from
          from t
          group by session_id
         ) tt
    where t.session_id = tt.session_id and
          (t.user_name is null or t.database_name is null or t.connection_from is null);

【讨论】:

  • 非常感谢。几乎工作了。 connection_from 列未更新。一个小收获。虽然 connection_from 列看起来像 null,但当我发出 select * from t where connection_from 为 null 时,不会返回任何行。你能指导我吗?再次感谢。
  • @vignesh28 。 . .将coalesce() 替换为case when t.connection_from > '' then t.connection_from else tt.connection_from end)
猜你喜欢
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多