MySQL Forums
Forum List  »  General

Re: How to delete one of double entries
Posted by: Peter Brawley
Date: April 30, 2015 11:29AM

Decide on a deletion rule, then code it. Suppose the rule is: for each unique (Positionsnummer, Positionsnummer_Alt, KrankId) value set, keep the row with the smallest id and delete the rest. Then the dupes to lose are in the id_to_lose column of this query ...

select 
  a.id_to_keep, a.Positionsnummer, a. Positionsnummer_Alt, a. KrankId, 
  b.id_to_lose, b.Positionsnummer, b. Positionsnummer_Alt, b. KrankId, 
from (                                                    -- subquery to find min ids
  select Positionsnummer, Positionsnummer_Alt, KrankId, min(id) as id_to_keep
  from positionen_neu 
  group by Positionsnummer, Positionsnummer_Alt, KrankId
) a
join (                                                    -- all rows matched on those 3 cols
  select id as id_to_lose, Positionsnummer, Positionsnummer_Alt, KrankId
  from positionen_neu 
) b using(Positionsnummer, Positionsnummer_Alt, KrankId)
where a.id_to_keep <> b.id_to_lose;

To build the deletion query, remove all Select expressions except id_to_lose from the above, then prepend deletion syntax:

delete from positionen_neu p
join (
  select b.id_to_lose, 
  from (
    select Positionsnummer, Positionsnummer_Alt, KrankId, min(id) as id_to_keep
    from positionen_neu 
    group by Positionsnummer, Positionsnummer_Alt, KrankId
  ) a
  join (            
    select id as id_to_lose, Positionsnummer, Positionsnummer_Alt, KrankId
    from positionen_neu 
  ) b using(Positionsnummer, Positionsnummer_Alt, KrankId)
where p.id_to_keep <> b.id_to_lose;

Options: ReplyQuote


Subject
Written By
Posted
Re: How to delete one of double entries
April 30, 2015 11:29AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.