Cómo corregir caracteres UTF8 de doble codificación (en una tabla utf-8)


Se ejecutó un LOAD DATA INFILE anterior asumiendo que el archivo CSV está codificado en latin1. Durante esta importación, los caracteres multibyte se interpretaron como dos caracteres individuales y luego se codificaron usando utf-8 (de nuevo).

Esta doble codificación creó anomalías como ñ en lugar de ñ.

Cómo corregir estas cadenas?

Author: vbence, 2012-07-11

2 answers

La siguiente función MySQL devolverá la cadena utf8 correcta después de la doble codificación:

CONVERT(CAST(CONVERT(field USING latin1) AS BINARY) USING utf8)

Se puede usar con una instrucción UPDATE para corregir los campos:

UPDATE tablename SET
    field = CONVERT(CAST(CONVERT(field USING latin1) AS BINARY) USING utf8);
 96
Author: vbence,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-11 15:56:26

La respuesta anterior funcionó para algunos de mis datos, pero resultó en muchas columnas NULAS después de ejecutarse. Mi pensamiento es que si la conversión no tuvo éxito devuelve null. Para evitar eso, agregué un pequeño cheque.

UPDATE
    tbl

SET
    col =
    CASE
        WHEN CONVERT(CAST(CONVERT(col USING latin1) AS BINARY) USING utf8) IS NULL THEN col
        ELSE CONVERT(CAST(CONVERT(col USING latin1) AS BINARY) USING utf8)
    END
 9
Author: Eric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 15:12:35