如何基于连接查询更新多行

pb3s4cty  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(260)

我有两个oracle表

Table A
----------
Fst_nm | Lst_nm | UserID | AppID 

Table B
----------
Fst_nm | Lst_nm | UserID | AppID

有些人同时存在于两个表中,有些人只存在于一个表中。两个表中都存在一些人,但表a中没有appid。我试图编写一个查询来联接这两个表,确定表a中没有appid但表b中确实有appid的人,并将相同的appid复制到表a中(这些箱子在这些table上不相配,所以需要额外的处理。)
以下是我目前掌握的情况:

UPDATE TABLE_A a
SET a.AppID = (SELECT b.AppID
                 FROM TABLE_A a
                 JOIN TABLE_B b
                 ON trim(upper(a.lst_nm))  = trim(upper(b.lst_nm))
                 AND trim(upper(a.fst_nm)) = trim(upper(b.fst_nm)) 
                 WHERE a.Appid is null
                 AND a.UserID IS NOT null
                 AND b.fst_nm IS NOT NULL
                 AND b.lst_nm IS NOT NULL)
WHERE a.AppID is null;

我可以理解我收到了这个错误: ORA-01427: single-row subquery returns more than one row 我可以根据select查询遍历并编写单独的update语句,但它大约有150条记录,希望在一个查询中完成。
有什么建议吗?
谢谢!

kh212irz

kh212irz1#

您不应再次从中选择 table_a 相反,在子查询中,您希望将其与外部查询相关联。检查中是否有相关匹配项 table_b ,您可以使用 exists 条件。
我认为你想要的逻辑是:

update table_a a
set a.appid = (
    select b.appid
    from table_b b
    where
        trim(upper(a.lst_nm))  = trim(upper(b.lst_nm))
        and trim(upper(a.fst_nm)) = trim(upper(b.fst_nm)) 
        and b.fst_nm is not null
        and b.lst_nm is not null
)
where 
    a.appid is null 
    and a.userid is not null
    and exists (
        select 1
        from table_b b
        where 
            trim(upper(a.lst_nm))  = trim(upper(b.lst_nm))
            and trim(upper(a.fst_nm)) = trim(upper(b.fst_nm)) 
            and b.fst_nm is not null
            and b.lst_nm is not null
    )

相关问题