Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL是否将一个联接表的多个记录分组?_Mysql_Sql_Grouping - Fatal编程技术网

Mysql SQL是否将一个联接表的多个记录分组?

Mysql SQL是否将一个联接表的多个记录分组?,mysql,sql,grouping,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

我有两张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

提前感谢。

在MySQL中,您需要使用将多行连接成一行的函数。由于这是一个聚合函数,您还将在查询中使用
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

结果是:

| 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 |
使用组_concat

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;