【问题标题】:Updating rows using select multiple tables postgres使用选择多个表 postgres 更新行
【发布时间】:2018-08-08 21:58:40
【问题描述】:

我有这些表和值:

Table1                 Table2                
------------------     --------              
ID | CREATED_BY        ID | NAME                   
------------------     --------              
1 |                    1  | aaa                  
2 |                    2  | bbb                   
3 |                    3  | ccc
4 |                    4  | ddd                    


Table1_2_link                                       
--------------------------                     
ID | TABLE1_ID | TABLE2_ID                                   
--------------------------                     
1 |  1         |   1                                
2 |  2         |   2                                  
3 |  3         |   3                        
4 |  3         |   4

我想用 Table2 中的名称值更新 Table1 中的 created_by 列,其中 Table1_2_link 只有一对(TABLE1_ID,TABLE2_ID)。

更新后的结果必须是:

Table1             
------------------ 
ID | CREATED_BY    
------------------ 
1 |  aaa           
2 |  bbb           
3 |                
4 |                

有没有办法通过简单的 SQL 查询来做到这一点?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您需要joinupdate

    update table1 t1
        set created_by = t2.name
        from (select t12.TABLE1_ID, max(t12.TABLE2_ID) as TABLE2_ID
              from Table1_2_link t12
              group by t12.TABLE1_ID
              having count(*) = 1
             ) t12 join
             table2 t2
             on t12.TABLE2_ID = t2.id
        where t12.TABLE1_ID = t1.id;
    

    Table1_2_link 上的子查询查找只有一行的 id。当只有一行时,MAX() 返回该行中TABLE2_ID 的值。

    【讨论】:

      【解决方案2】:

      请尝试以下查询:

      update Table1 as tt1
      SET CREATED_BY = tt1.NAME
      FROM(
      SELECT t1.ID, t3.NAME
      FROM Table1 t1
      INNER JOIN Table1_2_link t2 ON t1.id = t2.TABLE1_ID
      INNER JOIN Table2 t3 ON t2.TABLE2_ID = t3.ID)
      T
      where T.ID = tt1.ID
      

      【讨论】:

      • 查询更新还包含多对(TABLE1_ID、TABLE2_ID)的行。在我的示例中,表 1 的 ID 3 附加到表 2 中的 ID:3 和 4。此行不应更新。
      猜你喜欢
      • 2022-01-07
      • 2021-12-01
      • 1970-01-01
      • 2011-10-09
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多