lundi 13 juin 2016

Request values by relation field contain several id's separated by delimiter

I have dirty data model in some self written CMS , that i am trying to migrate data from. Relation filds in articles tables contains data like this:
table 1

id   fruits   countries
1    |1|2|3|   |1|2|3|

End in related tables i have:
table 2

id value
1  apple
2  banana
3  orange

table 3

id value
1  columbia
2  chili
3  peru

So i need to get after sql request: 1 apple,banana,orange columbia,chili,peru
Mean to request the related values and to replace "|" by ","
So i am using this sql:

select t1.id, group_concat(t2.value), group_concat(t3.value)
from table1 t1
join table2 t2 on find_in_set(t2.id,REPLACE(t1.fruits,'|',','))>0
join table3 t3 on find_in_set(t3.id, REPLACE(t1.countries,'|',','))>0 
group by t1.id;

And finally if in fruits column i have apple,banana,orange and in countries column i have only one value (peru) i get peru 3 times peru,peru,peru. And vice versa if i have in fruits apples and in cities peru,columbia i get apples,apples twice.

fruits                 countries
apple,banana,orange    peru,peru,peru

But must be:

fruits                 countries
apple,banana,orange    peru

Aucun commentaire:

Enregistrer un commentaire