Awn Ali
Awn Ali

Reputation: 1379

Insert Comma Separated values through MySQL query

I have one table (in phpmyadmin) with the following fields and structure:

Table 1
id  | sponsor
1   | -1 
2   | 1  
3   | 1  
4   | 2  
5   | 4  
6   | 4  

Now i want to insert data from above table into new table as below:

Table 2
id  | children
1   | 2,3
2   | 4 
3   |   
4   | 5,6
5   |   
6   |   

Actually this is Tree structure, which i have saved in mysql database.
I have already written a script in php but as there are more then 100K rows in table 1 so its taking too much time. Please tell me an efficient sql query to do this task quickly.

Upvotes: 4

Views: 3043

Answers (4)

Andriy M
Andriy M

Reputation: 77677

This is similar to @Justin's answer but uses a left join instead of a correlated subquery:

INSERT INTO Table2 (id, children)
SELECT
  sp.id,
  GROUP_CONCAT(ch.id) AS children
FROM Table1 sp
LEFT JOIN Table1 ch ON sp.id = ch.sponsor
GROUP BY t1.id
;

A demonstration of the SELECT statement's result can be found (and played with) at SQL Fiddle (the schema having been borrowed from Justin).

Upvotes: 2

Justin
Justin

Reputation: 9724

Query:

SQLFIDDLE Example

SELECT 
t1.id,
(SELECT group_concat(id separator ', ')
  FROM table1 t2
   WHERE t2.sponsor = t1.id) AS children
FROM table1 t1
GROUP BY t1.id

Result:

| ID | CHILDREN |
-----------------
|  1 |     2, 3 |
|  2 |        4 |
|  3 |   (null) |
|  4 |     5, 6 |
|  5 |   (null) |
|  6 |   (null) |

Insert Statement:

INSERT INTO table2
    SELECT 
    t1.id,
    (SELECT group_concat(id separator ', ')
      FROM table1 t2
       WHERE t2.sponsor = t1.id) AS children
    FROM table1 t1
    GROUP BY t1.id

Upvotes: 4

xelber
xelber

Reputation: 4637

See if the following helps

INSERT INTO table2
SELECT sponsor, GROUP_CONCAT(id)
FROM table1
GROUP BY id

Upvotes: 0

Frildoren
Frildoren

Reputation: 243

One of your SELECT elements should be a GROUP_CONCAT(...) as column, which will concatenate those values separated with commas. If you want to filter by one of those values, you can use GROUP BY -whatever- HAVING find_in_set( -number- , column )

Upvotes: 1

Related Questions