我有一个表(在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查询来快速完成这项任务。
发布于 2012-11-14 20:23:22
查询:
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语句:
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发布于 2012-11-14 21:18:24
这类似于@Justin's answer,但使用左连接而不是相关子查询:
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
;SELECT语句结果的演示可以在at SQL Fiddle (该模式是从Justin借用而来的)中找到(并使用)。
发布于 2012-11-14 19:31:08
您的选择元素之一应该是GROUP_CONCAT(...) as column,它将连接那些用逗号分隔的值。如果要按这些值之一进行过滤,可以使用GROUP BY -whatever- HAVING find_in_set( -number- , column )
https://stackoverflow.com/questions/13377911
复制相似问题