在 Oracle 上使用 concat 和 inner join 更新语句

Update statement with concat & inner join on Oracle

我正在尝试创建一个更新查询,将 table 中的 3 个字段连接到另一个 table

中的 1 个字段

第一个table叫table1

ID       DESC
12       left:Middle:Right

第二个tableTable2

ID  FLD1    FLD2    FLD3
12  left    Middle  Right

尝试用 table2 的值更新 Table1 上的所有 desc 字段,其中 table1.id = table2.id

update table1 A SET A.DESC = (SELECT CONCAT(B.fld1, ':', B.fld2, ':', B.fld3) 
                              from table2 B 
                              where A.ID = B.ID) 
Where A.id = 12;

但是,我从上面的查询中收到一条错误消息,提示“参数数量无效”知道我做错了什么吗?或者我怎样才能以更好的方式完成这项工作?

CONCAT 只接受两个参数,这意味着你必须使用嵌套的 CONCATs.

不过,您更愿意使用没有此类限制的双管道运算符 ||。所以:

update table1 A SET A.DESC = (SELECT B.fld1 ||':'|| B.fld2 ||':'|| B.fld3   --> this
                              from table2 B 
                              where A.ID = B.ID) 
Where A.id = 12;

要更新所有匹配的行,您可以

update table1 A SET A.DESC = (SELECT B.fld1 ||':'|| B.fld2 ||':'|| B.fld3   --> this
                              from table2 B 
                              where A.ID = B.ID) 
Where exists (select null
              from table2 b
              where a.id = b.id);

MERGE:

merge into table1 a
  using table2 b
  on (b.id = a.id)
  when matched then update set a.desc = b.fld1 ||':'|| b.fld2 ||':'|| b.fld3;

如果您有重复项,DISTINCT 可能会有所帮助,例如

update table1 a set 
  a.desc = (select distinct b.fld1 ||':'|| b.fld2 ||':'|| b.fld3
            from table2 b
            where a.id = b.id
           )
where exists ...

如果没有,那么您将不得不看看如何处理这些重复项。如果可能,请在 WHERE 子句中使用另一列。或者,如果您真的不关心哪个串联组合适合,请使用聚合函数,例如 MINMAX,例如

update table1 a set 
  a.desc = (select max(b.fld1 ||':'|| b.fld2 ||':'|| b.fld3)
            from table2 b
            where a.id = b.id
           )
where exists ...