[英]Insert Comma Separated values through MySQL query
我有一个表(在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 |
实际上这是Tree结构,我已经保存在mysql数据库中。
我已经在php中编写了一个脚本,但是因为表1中有超过100K的行所以它花了太多时间。 请告诉我一个有效的SQL查询来快速完成这项任务。
查询:
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
这与@ Justin的答案类似,但使用左连接而不是相关子查询:
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
;
可以在SQL Fiddle (从Justin借来的模式) 中找到(并使用)SELECT语句结果的演示。
SELECT元素之一应该是GROUP_CONCAT(...) as column
,它将连接用逗号分隔的值。 如果GROUP BY -whatever- HAVING find_in_set( -number- , column )
其中一个值进行过滤,可以使用GROUP BY -whatever- HAVING find_in_set( -number- , column )
看看以下是否有帮助
INSERT INTO table2
SELECT sponsor, GROUP_CONCAT(id)
FROM table1
GROUP BY id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.