我有一个表(在phpmyadmin中)具有以下字段和结构:

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

现在我想将数据从上表插入到新表中,如下所示:
Table 2
id  | children
1   | 2,3
2   | 4
3   |
4   | 5,6
5   |
6   |

其实这是树状结构,我已经保存在mysql数据库中。
我已经在php中编写了一个脚本,但是由于表1中有超过100K的行,因此花费了太多时间。请告诉我一个有效的sql查询,以快速完成此任务。

最佳答案

查询:

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

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

插入语句:
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

09-25 17:55
查看更多