按UNION结果分组

时间:2016-10-19 18:56:53

标签: sql postgresql

我有2张桌子:'父母'和孩子'

CHILD:

ID  |   NAME        | PARENT_ID
--------------------------------
1   |   Child 1     |   1
2   |   Child 2     |   1
3   |   Child 3     |   1
4   |   Child 4     |   1
5   |   Child 5     |   1
6   |   Child 6     |   2
7   |   Child 7     |   2
8   |   Child 8     |   2
9   |   Child 9     |   2
10  |   Child 10    |   2
11  |   Child 11    |   2
12  |   Child 12    |   2
13  |   Child 13    |   2
14  |   Child 14    |   2
15  |   Child 15    |   3
16  |   Child 16    |   3
17  |   Child 17    |   3

PARENT:

ID  |   NAME        |   UNIQUE_ID
----------------------------------
1   |   PARENT 1    |   uniq-001
2   |   PARENT 2    |   uniq-002
3   |   PARENT 3    |   uniq-003

我想结合这两个表并得到像这样的结果

ID  |   NAME        |   PARENT_ID
---------------------------------
1   |   parent 1    |   1
1   |   child 1     |   1
2   |   child 2     |   1
2   |   parent 2    |   2
6   |   child 6     |   2
7   |   child 7     |   2
12  |   child 12    |   2
13  |   child 13    |   2
14  |   child 14    |   2
3   |   parent 3    |   3
15  |   child 15    |   3

我的sql代码看起来像

select * from 
(
SELECT 
    id, 
    name,
    id as parent_id
from 
    parent
UNION all
SELECT 
    id, 
    name,
    parent_id
from 
    child
) t
group by 3, 1, 2

我不知道为什么,但结果没有按PARENT_ID分组。 如何按PARENT_ID对此查询进行分组?

1 个答案:

答案 0 :(得分:1)

我担心这个问题不够明确。 以下是两个开始的建议。

嘟嘟

select      id
           ,name
           ,unique_id

from        (           select 2,id,parent_id,name,null      from child
            union all   select 1,id,id       ,name,unique_id from parent
            ) t (source_order,id,pid,name,unique_id)

order by    pid
           ,source_order
           ,id
;
id      name        unique_id
--      ----        ---------
1       PARENT 1    uniq-001
1       Child 1     
2       Child 2     
3       Child 3     
4       Child 4     
5       Child 5     
2       PARENT 2    uniq-002
6       Child 6     
7       Child 7     
8       Child 8     
9       Child 9     
10      Child 10    
11      Child 11    
12      Child 12    
13      Child 13    
14      Child 14    
3       PARENT 3    uniq-003
15      Child 15    
16      Child 16    
17      Child 17   
select      p.*
           ,(select array_agg ('(' || c.id || ') ' || c.name order by c.id) from child as c where c.parent_id = p.id)   as children

from        parent as p

order by    p.id
;
id  name        unique_id   childrn
--  ----        ---------   -------
1   PARENT 1    uniq-001    (1) Child 1 ,(2) Child 2 ,(3) Child 3 ,(4) Child 4 ,(5) Child 5 
2   PARENT 2    uniq-002    (6) Child 6 ,(7) Child 7 ,(8) Child 8 ,(9) Child 9 ,(10) Child 10,(11) Child 11,(12) Child 12,(13) Child 13,(14) Child 14
3   PARENT 3    uniq-003    (15) Child 15,(16) Child 16,(17) Child 17