0

I have two tables:

  • table 1 with id, firstname and lastname
  • table 2 with t1_id, firstname and lastname
  • I'd like a SQL query (if possible, not a PL/SQL) to update table2 with table1's id when I have a unique match on firstname and lastname

    the word "unique" here is my problem :

    update table2 t2
    set t1_id = (select id from table1 t1
        where t1.firstname=t2.lastname and t1.lastname=t2.lastname)
    

    Whenever I have a match from t2 to multiple t1 records, I get the "ORA-01427: single-row subquery returns more than one row" error. Any clue to not update on multiple matches?

    Thanks.

    4

    4 回答 4

    1
    merge into table2 d
    using (
      select firstname, lastname, max(id) id
      from table1 t1
      group by firstname, lastname
      having count(0) = 1
    ) s
    on (d.firstname=s.firstname and d.lastname=s.lastname)
    when matched then update set t1_id = s.id;
    
    于 2013-09-19T17:00:32.663 回答
    0

    如果您想将 id 设置为 NULL 以防在 table1 中发现重复条目​​或根本没有条目,那么只需:

    更新表 2 t2
    设置 t1_id =
    (
      当 min(id) = max(id) then min(id) else null end 时选择 case
      从表 1 t1
      其中 t1.firstname=t2.lastname 和 t1.lastname=t2.lastname
    )
    
    于 2013-09-19T19:02:22.367 回答
    0

    内部联接可以工作(至少对于 SQL Server)。

    update  t1
    set t1.id = t2.id 
    FROM table1 t1 
    INNER JOIN table t2 ON t1.firstname=t2.firstname and t1.lastname=t2.lastname
    
    于 2013-09-19T16:33:33.977 回答
    0

    可能的解决方案是计算匹配的行数:

    update table2 t2
    set t1_id = 
                (
                 select id 
                 from table1 t1
                 where t1.firstname=t2.lastname and t1.lastname=t2.lastname
                )
    where 
    (
     select count(*) 
     from table1 
     where t1.firstname = lastname and t1.lastname= lastname
    ) = 1
    
    于 2013-09-19T16:41:01.377 回答