【问题标题】:How to update column in one table from other table without common key如何在没有公用键的情况下从另一个表中更新一个表中的列
【发布时间】:2019-07-16 16:12:54
【问题描述】:

这可能是非常基本的,但我不知道要搜索什么。

Table1:

someid value
1      0
2      0
3      0

Table2:

someid value
9      1
10     2
11     3

我想用Table2.value 值逐行更新Table1.value,没有公共键,没有where 子句,只有table1.value row1 = table2.value row1 等。就像一个水平联合。

所以 Table1 应该是:

someid value
1      1
2      2
3      3

我试试:

update table1
set value = table2.value
from table2

但所有值都来自 table2 的第一行:

1   1
2   1
3   1

【问题讨论】:

    标签: sql postgresql sql-update window-functions


    【解决方案1】:

    你可以使用row_number():

    update table1 
    set value = t2.value
    from (
      select id, value, row_number() OVER (ORDER BY id) AS n from table1
    ) t inner join (
      select id, value, row_number() OVER (ORDER BY id) AS n from table2
    ) t2 on t.n = t2.n
    where t.id = table1.id
    

    请参阅demo
    表 1 的结果:

    > id | value
    > -: | ----:
    >  1 |     1
    >  2 |     2
    >  3 |     3
    

    如果你确定table1中的id是连续的,没有间隔,并且从1开始,那么查询可以简化成这样:

    update table1 
    set value = t2.value
    from (
      select id, value, row_number() OVER (ORDER BY id) AS n from table2
    ) t2 
    where t2.n = table1.id
    

    请参阅demo

    【讨论】:

      【解决方案2】:

      你可以试试下面的带有row_number()窗口解析函数的sql语句:

      with t as
      ( 
       select row_number() over (order by someid) as someid,
              value
         from table2
      )
      update table1 t1
         set value = t.value
        from t
       where t1.someid = t.someid
      returning t.*;
      
      someid  value
      1       1
      2       2
      3       2
      

      那些返回值来自table1

      Demo

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 2011-04-22
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 1970-01-01
        • 2013-04-09
        相关资源
        最近更新 更多