0

此查询为我提供了几行以及来自usingtable1的相关记录。我已将 table2 中的行限制为每行 10 行。table2left join lateral

select t1.id, array_agg(t2.column1) 
from table1 t1 
left join lateral (select * from table2 where table1_id = t1.id order by column2 limit 10) t2 on true 
where t1.other = other_value
group by t1.id

但是我怎样才能包含count(*)table2 中与 table1 ( select count(*) from table2 where table1_id = t1.id) 相关的所有记录的总数。由于我正在进行横向连接,我不确定如何添加这些结果。

我可以重用我已经在做的横向连接,还是我必须做一个单独的横向连接,因为第一个有 alimit 10并且count(*)不需要限制?查询应该是什么样子才能使它像这样工作?(我认为可能有一种方法可以使用第一个横向连接中的数组切片语法来做到这一点,但我认为这会很昂贵,因为它必须获取所有行才能获得它们的计数。)

4

1 回答 1

1

您不妨为此使用窗口函数:

select t1.id, array_agg(t2.column1) 
from table1 t1 left join
     (select t2.*, count(*) over (partition by table1_id) as cnt,
             row_number() over (partition by table1_id order by column2) as seqnum
      from table2
     ) t2
     on t2.table1_id = t1.id and sequm <= 10
where t1.other = other_value 
group by t1.id;

您可以将其作为单独的lateral join.

编辑:

使用单独的横向连接:

select t1.id, array_agg(t2.column1), t2c.cnt
from table1 t1 left join lateral
     (select *
      from table2
      where table1_id = t1.id
      order by column2
      limit 10
     ) t2
     on true left join lateral
     (select count(*) as cnt
      from table2
      where table1_id = t1.id
     ) t2c
     on true
where t1.other = other_value
group by t1.id, t2.cnt;

或者在外部查询中使用没有聚合的单个横向连接:

select t1.id, t2.column1s, t2.cnt
from table1 t1 left join lateral
     (select array_agg(t2.column1) as column1, max(cnt) as cnt
      from (select t2.*,
                   row_number() over (order by column2 desc) as seqnum,
                   count(*) over () as cnt
            from table2
            where table1_id = t1.id
           ) t2
      where seqnum <= 10
     ) t2
     on true left join 
where t1.other = other_value;

这可能是最好的方法。

于 2020-04-27T13:03:33.087 回答