mysql多个字段合并;
SELECT DISTINCT
-> parent_id, child_id
-> FROM group_c
-> ORDER BY parent_id;
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
| 2 | 6 |
| 3 | 1 |
| 3 | 2 |
| 4 | 1 |
| 5 | 0 |
+-----------+----------+
12 rows in set (0.00 sec)
可以看到,parent_id和child_id是一对多的情况
而如果使用group_concat函数,则
SELECT DISTINCT
-> parent_id, GROUP_CONCAT(DISTINCT child_id ORDER BY child_id) AS child_id_list
-> FROM group_c
-> group by parent_id
-> ORDER BY parent_id;
+-----------+---------------+
| parent_id | child_id_list |
+-----------+---------------+
| 1 | 1,2,3,4 |
| 2 | 1,3,4,6 |
| 3 | 1,2 |
| 4 | 1 |
| 5 | 0 |
+-----------+---------------+
5 rows in set (0.00 sec)
可以看到,其具体区别了,默认是用逗号分隔的;
SELECT DISTINCT
-> parent_id, child_id
-> FROM group_c
-> ORDER BY parent_id;
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
| 2 | 6 |
| 3 | 1 |
| 3 | 2 |
| 4 | 1 |
| 5 | 0 |
+-----------+----------+
12 rows in set (0.00 sec)
可以看到,parent_id和child_id是一对多的情况
而如果使用group_concat函数,则
SELECT DISTINCT
-> parent_id, GROUP_CONCAT(DISTINCT child_id ORDER BY child_id) AS child_id_list
-> FROM group_c
-> group by parent_id
-> ORDER BY parent_id;
+-----------+---------------+
| parent_id | child_id_list |
+-----------+---------------+
| 1 | 1,2,3,4 |
| 2 | 1,3,4,6 |
| 3 | 1,2 |
| 4 | 1 |
| 5 | 0 |
+-----------+---------------+
5 rows in set (0.00 sec)
可以看到,其具体区别了,默认是用逗号分隔的;