1

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

提前致谢。

4

2 回答 2

0

In MySQL you will want to use the GROUP_CONCAT() function which will concatenate the multiple rows into a single row. Since this is an aggregate function, you will also use a GROUP BY clause on the query:

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

See SQL Fiddle with Demo.

The result is:

| 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 |
于 2013-02-21T12:19:34.857 回答
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;

小提琴

于 2013-02-21T12:23:38.960 回答