Mysql
 SQL >> Database >  >> RDS >> Mysql

Cancellare righe duplicate e aggiornare la tabella delle relazioni

Questa procedura individua gli elementi duplicati, redireziona la tabella delle relazioni sulla riga che sopravvive e poi rimuove il duplicato:

begin
  for x in (
    -- find duplicate items
    select * from (
      select rowid row_id, item_id, item_description,
             row_number() over(partition by item_description order by item_description) row_no
      from item_tab
    ) where row_no > 1
  ) loop
    -- replaceing duplicate Items
    update menu_has_item
    set menu_has_item.item_tab_item_id = (
      select item_id from (
        select item_id,
               row_number() over(partition by item_description order by item_description) row_no
        from item_tab
        where item_tab.item_description = x.item_description
      ) where row_no = 1
    )
    where menu_has_item.item_tab_item_id = x.item_id;

    -- deleting duplicate items
    delete item_tab where rowid = x.row_id;
  end loop;
  -- commit;
end;

Usare row_number() partizionato per descrizione mantiene la prima occorrenza e segnala le altre per la rimozione. Attenzione all'ordine: prima si spostano i riferimenti, poi si cancella il duplicato.