在postgresql 9.3中更新多列的问题

时间:2016-11-18 18:48:33

标签: postgresql

我想根据电话表更新配置文件表中的三列。它没有工作,并收到错误消息:

ERROR:  syntax error at or near "home_phone"
LINE 2:                       set home_phone = (select number from p..

电话表样本:

_id phone.type  phone.number
51b20fac6ddbfdb704000034    Office  403-244-1895
57b6204d7065a6a5550fe30b    Mobile  123-4567
57b6204d7065a6a5550fe30b    Home    765-4321
57e99f88b948da6c3be04366    Mobile  250-851-1041
51b20fac6ddbfdb704000007    Home    555-555-5555

脚本:

update profiles f set office_phone = (select number from phone_tmp p where p._id = f._userid and type ='Office'),
                      set home_phone = (select number from phone_tmp p where p._id = f._userid and type ='home'),
                      set mobile =(select number from phone_tmp p where p._id = f._userid and type ='mobile') ;    

电话表中的值_id与配置文件表中的_userid相同。 我感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:3)

正如错误所说 - 查询语法错误。 试试这个:

update profiles f set office_phone = (select number from phone_tmp p where p._id = f._userid and type ='Office'),
                   home_phone = (select number from phone_tmp p where p._id = f._userid and type ='home'),
                   mobile =(select number from phone_tmp p where p._id = f._userid and type ='mobile'); 

您应该只使用一个SET关键字,并使用逗号分隔特定的分配。

答案 1 :(得分:2)

最有效的方法是首先创建一个语句,将行转换为列,然后将其用作update语句的源:

update profiles f 
  set office_phone = t.office_phone, 
      home_phone = t.home_phone,
      mobile = t.mobile
from (
  select _id, 
         max(case when type = 'Office' then number end) as office_phone, 
         max(case when type = 'Home' then number end) as home_phone,
         max(case when type = 'Mobile' then number end) as mobile
   from phone_tmp
   group by _id
) t 
where t._id = f.userid;

在线示例:http://rextester.com/WUA44201