[英]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.