php – 通过MySQL查询插入逗号分隔值
发布时间:2020-12-13 17:43:06 所属栏目:PHP教程 来源:网络整理
导读:我有一个表(在phpmyadmin中)具有以下字段和结构: Table 1id | sponsor1 | -1 2 | 1 3 | 1 4 | 2 5 | 4 6 | 4 现在我想将上表中的数据插入到新表中,如下所示: Table 2id | children1 | 2,32 | 4 3 | 4 | 5,65 | 6 | 实际上这是Tree结构,我已经保存在mysql数
我有一个表(在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数据库中. 解决方法
查询:
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,') FROM table1 t2 WHERE t2.sponsor = t1.id) AS children FROM table1 t1 GROUP BY t1.id (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |