Mysql get comma separated list of columns

927 views Asked by At

I have a column with accessories of products as below example:

TABLE1

ProductID    accessories
1            2,3  
2            1,4,5
3
4            1
5            2

It means that for the PRODUCT 2, it has the accessories product ids 1,4 and 5

and i have THE FINAL table 2 below which look like this

TABLE2

GRP     ProductID     accessories 
a       2             
b       3             
c       1             
d       4             
e       5 

so actually if using UPDATE it would be like this

TABLE2

UPDATE table t2
INNER JOIN table1 t1
On t2.ProductID = t1.ProductID
set t2.accessories = t1.accessories 

GRP     ProductID     accessories
a       2             1,4,5
b       3              
c       1             2,3
d       4             1
e       5             2

but i want to change the productIDs in the t2.accessories with the GRP character instead according to the t2.ProductID so that the FINAL table looks like this .

TABLE2

GRP     ProductID     accessories
a       2             c,d,e
b       3              
c       1             a,b
d       4             c
e       5             a

iam really confused how to do that correctly i was able to handle this using php code, but it takes loong time becouse i have 100k products therefore i prefer to use some group_concat or concat_ws to handle this

and some t2.accessories may already be stored, therefore it should be distinct values, so there is no duplicate t2.accessories on table2

Here is the tables http://sqlfiddle.com/#!9/bfddf

2

There are 2 answers

6
Gordon Linoff On

You should fix your data structure to have a junction table. Don't store lists as strings. SQL has a perfectly good way to store lists; it is called a table. Don't store numbers as strings. SQL has very good data types for numbers. They do not contain "char" in their name.

There is a way to do what you want in the database, but you can't complain about performance. Structure your data correctly and it will go faster.

The select query that does the concatenation looks like this:

select t1.productid,
       group_concat(t2.productid order by find_in_set(t2.ProductId, t1.accessories))
from table1 t1 join
     table2 t2
     on find_in_set(t2.ProductId, t1.accessories) > 0
group by t1.productid;

But, you should really fix your data structure.

0
inventor On

This worked as i wanted.

UPDATE table2 
INNER JOIN ( 
            select t1.productid, group_concat(t2.GRP order by find_in_set(t2.GRP, t1.accessories)) as test from table1 t1 
            join table2 t2 on find_in_set(t2.ProductId, t1.accessories) > 0 group by t1.productid
            ) as temp on table2.ProductId=temp.productid
set table2.accessories=temp.test

The only problem is, if you have large amount of rows, it will take loong time