2013-02-21 79 views
1

我有兩個MySQL表SQL將一個連接表的多個記錄分組?

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 

是否有一個SQL在MySQL中查詢可以返回類似這樣的內容

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 

在此先感謝。

回答

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 |