postgresql 在一个结果中显示两个子列表
postgresql display two sublists in one result
假设架构非常简单
table主要
main_id, ...
1 , ...
2 , ...
table sub1
main_id, sub1_data
1 , a
1 , b
2 , g
table sub2
main_id, sub2_data
1 , 1
2 , 1
2 , 2
作为我想要的输出
main_id, sub1_data, sub2_data
1 , a , 1
1 , b , <null>
2 , g , 1
2 , <null> , 2
使用联合我可以接近但每个列表都有自己的行
SELECT main_id, sub1_data, NULL
FROM sub1
UNION
SELECT main_id, NULL, sub2_data
FROM sub2
结果
main_id, sub1_data, sub2_data
1 , a , <null>
1 , b , <null>
1 , <null> , 1
2 , g , <null>
2 , <null> , 1
2 , <null> , 2
那么有没有办法让它们共享两个行,并且只使用与最长列表一样多的行?
可以为您提供此 "interleaved" 输出的一件事是 unnest()
function with multiple parameters (or its equivalent: the ROWS FROM(...)
construct):
Table functions may also be combined using the ROWS FROM
syntax, with the results returned in parallel columns; the number of result rows in this case is that of the largest function result, with smaller results padded with null
values to match.
...
The special table function UNNEST
may be called with any number of array parameters, and it returns a corresponding number of columns, as if UNNEST
had been called on each parameter separately and combined using the ROWS FROM
construct.
select main_id, sub1_data, sub2_data
from (select main_id, array_agg(sub1_data) sub1_arr from sub1 group by main_id) s1
full join (select main_id, array_agg(sub2_data) sub2_arr from sub2 group by main_id) s2 using (main_id)
cross join unnest(sub1_arr, sub2_arr) u(sub1_data, sub2_data)
http://rextester.com/QSWESJ84203
注意:这是"relatively"新功能:它是在9.4
中引入的
假设架构非常简单
table主要
main_id, ...
1 , ...
2 , ...
table sub1
main_id, sub1_data
1 , a
1 , b
2 , g
table sub2
main_id, sub2_data
1 , 1
2 , 1
2 , 2
作为我想要的输出
main_id, sub1_data, sub2_data
1 , a , 1
1 , b , <null>
2 , g , 1
2 , <null> , 2
使用联合我可以接近但每个列表都有自己的行
SELECT main_id, sub1_data, NULL
FROM sub1
UNION
SELECT main_id, NULL, sub2_data
FROM sub2
结果
main_id, sub1_data, sub2_data
1 , a , <null>
1 , b , <null>
1 , <null> , 1
2 , g , <null>
2 , <null> , 1
2 , <null> , 2
那么有没有办法让它们共享两个行,并且只使用与最长列表一样多的行?
可以为您提供此 "interleaved" 输出的一件事是 unnest()
function with multiple parameters (or its equivalent: the ROWS FROM(...)
construct):
Table functions may also be combined using the
ROWS FROM
syntax, with the results returned in parallel columns; the number of result rows in this case is that of the largest function result, with smaller results padded with null values to match.
...
The special table functionUNNEST
may be called with any number of array parameters, and it returns a corresponding number of columns, as ifUNNEST
had been called on each parameter separately and combined using theROWS FROM
construct.
select main_id, sub1_data, sub2_data
from (select main_id, array_agg(sub1_data) sub1_arr from sub1 group by main_id) s1
full join (select main_id, array_agg(sub2_data) sub2_arr from sub2 group by main_id) s2 using (main_id)
cross join unnest(sub1_arr, sub2_arr) u(sub1_data, sub2_data)
http://rextester.com/QSWESJ84203
注意:这是"relatively"新功能:它是在9.4
中引入的