表1
id | sub1 | sub2 | sub3 1 | KK Nagar | Alwartirunagar | 1 | Valasaravakkam | Nandambakkam | Ramapuram 1 | Porur | Meenambakkam | Ashok Nagar 1 | Anna Nagar | Kodambakkam | Nungambakkam 2 | West Mambalam | Virugambakkam | T Nagar 2 | KK Nagar | |
如何在单个列中的新表中插入值,如id为sub1,sub2和sub3值组
答案 0 :(得分:1)
只需将group concat与group by选项一起使用,如下所示 - 你的主要表 -
| id | sub1 | sub2 | sub3 |
| 1 | kk nagar | Alwartirunagar | | | 1 | Valasaravakkam | Nandambakkam | Ramapuram | | 1 | Porur | Meenambakkam | Ashok Nagar | | 1 | Anna Nagar | Kodambakkam | Nungambakkam | | 2 | West Mambalam | Virugambakkam | T Nagar | | 2 | KK Nagar | | |
现在,当您运行查询时 - 从id t1 group中选择id,group_concat(sub1,' |',sub2); 它会为您提供如下数据
| id | group_concat(sub1,',',sub2,',',sub3)| | 1 | kk nagar,Alwartirunagar ,, Valasaravakkam,Nandambakkam,Ramapuram,Porur,Meenambakkam,Ashok Nagar,Anna Nagar,Kodambakkam,Nungambakkam | | 2 | West Mambalam,Virugambakkam,T Nagar,KK Nagar ,, |
现在只需通过以下查询将此数据插入另一个表中 插入到t2中按t1从t1组中选择id,group_concat(sub1,',',sub2,',',sub3);
现在您将获得t2中的数据,如下所示
| id | grouped_sub |
| 1 | kk nagar,Alwartirunagar ,, Valasaravakkam,Nandambakkam,Ramapuram,Porur,Meenambakkam,Ashok Nagar,Anna Nagar,Kodambakkam,Nungambakkam |
| 2 | West Mambalam,Virugambakkam,T Nagar,KK Nagar,
希望这会对你有所帮助。
注意: - 由于问题要求不同 - 查询 - 插入到t2 select * from(选择id,sub1作为主题从t1 union select id,sub2作为主题从t1 union select id,sub3作为subject来自t1)temp where subject!=''按ID排序;
| id | grouped_sub | + ------ + ---------------- + | 1 | Nungambakkam | | 1 | Alwartirunagar | | 1 | Ramapuram | | 1 | Porur | | 1 | Kodambakkam | | 1 | kk nagar | | 1 | Nandambakkam | | 1 | Ashok Nagar | | 1 | Anna Nagar | | 1 | Valasaravakkam | | 1 | Meenambakkam | | 2 | West Mambalam | | 2 | T Nagar | | 2 | KK Nagar | | 2 | Virugambakkam |