SQL将多个连接表的记录分组?

时间:2013-02-21 12:15:07

标签: mysql sql grouping

我有两个MySQL表

Parent
id, name
1, Parent 1
2, Parent 2

Children
id, parent_id, name
1,1, Child P1 1
2,1, Child P1 2
3,2, Child P2 1
4,2, Child P2 2
5,2, Child P2 3

我知道从两个表中获取记录的SQL是

Select Parent.id, Parent.name, Children.id, Children.name 
from Parent
left join Children 
  on Children.parent_id=Parent.id

这将返回类似

的内容
Parent.id  Parent.name    Children.id    Children.Name
1          Parent 1       1              Child P1 1
1          Parent 1       2              Child P1 2
2          Parent 2       3              Child P2 1
2          Parent 2       4              Child P2 2
2          Parent 2       5              Child P2 3

MySQL中是否存在可以返回此类内容的SQL查询

Parent.id  Parent.name    Children_ids    Children_Names
1          Parent 1       1,2            Child P1 1,Child P1 2
2          Parent 2       3,4,5          Child P2 1,Child P2 2,Child P2 3

提前致谢。

2 个答案:

答案 0 :(得分:0)

在MySQL中,您将需要使用GROUP_CONCAT()函数,该函数将多行连接成一行。由于这是一个聚合函数,因此您还将在查询中使用GROUP BY子句:

select p.id,
  p.name,
  group_concat(c.id order by c.id) ChildrenIds,
  group_concat(c.name order by c.id) ChildrenNames
from parent p
left join children c
  on p.id = c.parent_id
group by p.id, p.name

请参阅SQL Fiddle with Demo

结果是:

| ID |     NAME | CHILDRENIDS |                    CHILDRENNAMES |
------------------------------------------------------------------
|  1 | Parent 1 |         1,2 |            Child P1 1,Child P1 2 |
|  2 | Parent 2 |       3,4,5 | Child P2 1,Child P2 2,Child P2 3 |

答案 1 :(得分:0)

使用group_concat http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php

Select Parent.id, Parent.name, group_concat(Children.id) AS 'Children_ids',
group_concat(Children.name)  AS 'Children_Names'
from Parent left join Children on Children.parent_id=Parent.id
group by Parent.id, Parent.name;

fiddle