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

MySQL: normalizzare un campo separato da virgole

Per trasformare valori come a,b,c in righe distinte, MySQL mette a disposizione SUBSTRING_INDEX(). Quando si passa un indice negativo, l’estrazione parte dalla parte opposta della stringa.

create table TAGS (T_ID int auto_increment primary key, T_Name varchar(18));
insert ignore into TAGS (T_Name) select substring_index(RES_Tags, ',', 1) from RESOURCES;
insert ignore into TAGS (T_Name) select substring_index(substring_index(RES_Tags, ',', 2), ',', -1) from RESOURCES;
-- ripeti per il numero massimo di tag previsti
create table New_TAGS like TAGS;
insert into New_TAGS (T_Name) select distinct trim(T_Name) from TAGS;
drop table TAGS;
rename table New_TAGS to TAGS;

Il risultato è una tabella di tag puliti, senza duplicati e senza spazi in eccesso.