使用组合列更新另一个表中的列

时间:2015-05-10 21:47:39

标签: sql postgresql

所以我有两个表:survey和survey_ids,我实际上是将来自survey_ids的一些数据迁移到调查中。

'survey'有一个名为dist_string的列,理想情况下应该是survey_ids中列'dist_admin'和'dist_user'的组合。

我想对survey.dist_string(当前所有记录都是')进行更新,同时将两列survey_ids.dist_admin和survey_ids.dist_user合并到survey.dist_string中,但我有点陷入困境。我在调查表中有其他列没有空约束,所以如果我尝试插入dist_string,我会遇到问题。从survey_ids插入的其他列中已有数据。

来自survey_ids:

X = ((e^-lambda)*(lambda^n))/n!
ln X = -lambda + n*ln(lambda) - Sum (ln(n))
return e^X

我希望调查中的dist_string看起来像

 dist_admin    | dist_user
 --------------+--------------
               | 456dfghjk46
  0987ghasdf7  |
               | 123ghjwe46c
               | 5thw67de523
  4r5thgffghk  | 
  2qrt75434th  | 
               | 876tjheg3wg
  9uh7ygwedf6  | 

我如何做到这一点?

编辑:@coalesce,当我这样做时,我得到了dist_string:

  dist_string   
 -------------
  456dfghjk46   
  0987ghasdf7
  123ghjwe46c
  5thw67de523 
  4r5thgffghk
  2qrt75434th
  876tjheg3wg 
  9uh7ygwedf6

2 个答案:

答案 0 :(得分:1)

您可以使用COALESCE选择两列的非空值:

select coalesce(dist_admin, dist_user);

所以你的更新应该是:

update surveys set dist_sting = coalesce(NULLIF(dist_admin,'') , NULLIF(dist_user,'') )
 FROM survey_ids  WHERE  surveys.id = survey_ids.id;

答案 1 :(得分:0)

来自

SELECT * FROM survey_ids;
┌────┬────────────┬───────────┐
│ id │ dist_admin │ dist_user │
├────┼────────────┼───────────┤
│  1 │ (null)     │ ab1       │
│  2 │ cd2        │ (null)    │
└────┴────────────┴───────────┘
(2 rows)

SELECT * FROM surveys;          
┌────┬─────────────┐
│ id │ dist_string │
├────┼─────────────┤
│  1 │             │
│  2 │             │
└────┴─────────────┘
(2 rows)

运行

UPDATE surveys
SET dist_string = COALESCE(dist_admin, dist_user)
  FROM survey_ids
  WHERE surveys.id = survey_ids.id
;

surveys更新为:

SELECT * FROM surveys;
┌────┬─────────────┐
│ id │ dist_string │
├────┼─────────────┤
│  1 │ ab1         │
│  2 │ cd2         │
└────┴─────────────┘
(2 rows)

如果值NULL不是空字符串,请使用:

UPDATE surveys   
SET dist_string = CASE WHEN dist_user = '' THEN dist_admin ELSE dist_user END
  FROM survey_ids
  WHERE surveys.id = survey_ids.id
;

或混合两者(如果你有空字符串和NULL s):

UPDATE surveys   
SET dist_string = CASE 
                    WHEN dist_user = '' THEN dist_admin
                    WHEN dist_admin = '' THEN dist_user
                    ELSE COALESCE(dist_admin, dist_user)
                  END
  FROM survey_ids
  WHERE surveys.id = survey_ids.id
;
相关问题