Mysql
 sql >> Database >  >> RDS >> Mysql

Come modificare le righe duplicate in valori univoci in MySQL?

questo è un po 'complicato.. Ho testato sul mio host locale e fa quello che vuoi.. fammi sapere se hai domande. SQL FIDDLE

UPDATE temp t1, 
(
    SELECT 
        id as unique_id, 
        new_name 
    FROM(
        SELECT
          id,
          IF(@ROW = Name, @COUNT, @COUNT := 1),
          CONCAT(Name, ' - ', @COUNT) AS new_name,
          @ROW := Name,
          @COUNT := @COUNT + 1
        FROM temp
        JOIN (SELECT @COUNT := 0, @ROW := "") AS t
        WHERE Name IN(SELECT Name FROM temp
        GROUP BY Name
        HAVING COUNT(Name) > 1)
    ) AS temp_test
) as testing
SET t1.Name = testing.new_name where t1.id = testing.unique_id

L'output finale è simile al seguente:IMMAGINE

MODIFICA: Questo potrebbe funzionare meglio per motivi di prestazioni

1. PRIMA ESEGUIRE QUESTA QUERY

SET SESSION group_concat_max_len = 1000000;  -- longer if needed
SET @query1 := (
SELECT 
    GROUP_CONCAT(DISTINCT unique_name) 
FROM temp
JOIN(
    select Name as unique_name
    FROM temp
    GROUP BY name
    HAVING COUNT(Name) > 1
) as t
);

2. ALLORA ESEGUI QUESTO AGGIORNAMENTO

UPDATE temp t1, 
(
    SELECT 
        id as unique_id, 
        new_name 
    FROM(
        SELECT
          id,
          IF(@ROW = Name, @COUNT, @COUNT := 1),
          CONCAT(Name, ' - ', @COUNT) AS new_name,
          @ROW := Name,
          @COUNT := @COUNT + 1
        FROM temp
        JOIN (SELECT @COUNT := 0, @ROW := "") AS t
        WHERE FIND_IN_SET (`name`, @query1)
    ) AS temp_test
) as testing
SET t1.Name = testing.new_name where t1.id = testing.unique_id

L'ho testato sul mio locale e funziona, quindi dovresti essere in grado di farlo funzionare :)