根据日期联接表

时间:2019-10-21 08:57:50

标签: sql postgresql join greatest-n-per-group

我有两个表:

表A

ID | name
---+----------
 1 | example
 2 | example2

表B(created字段为timestamptz

ID | id_table_a | dek  | created
---+------------+------+---------------------
 1 |    1       | deka | 2019-10-21 10:00:00
 2 |    2       | dekb | 2019-10-21 11:00:00
 3 |    1       | dekc | 2019-10-21 09:00:00
 4 |    2       | dekd | 2019-10-21 09:40:00
 5 |    1       | deke | 2019-10-21 09:21:00

我需要从Table A获取记录,并且每条记录应具有基于dek的{​​{1}}中的最后table b

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我会使用横向连接,通常这比使用select max()

select a.*, b.dek
from table_a a
  join lateral (
    select id, id_table_a, dek, created
    from table_b 
    where b.id_table_a = a.id
    order by created desc 
    limit 1
  ) tb on true;

另一种替代方法是使用distinct on

select a.*, b.dek
from table_a a
  join lateral (
    select distinct on (id_table_a) id, id_table_a, dek, created
    from table_b 
    order by id_table_a, created desc
  ) tb on tb.id_table_a = a.id;

这取决于您的数据分布,哪个更快。

答案 1 :(得分:0)

使用CTE返回联接的表和NOT EXISTS

with cte as (
  select a.id, a.name, b.dek, b.created
  from tablea a inner join tableb b
  on b.id_table_a = a.id
)
select t.* from cte t
where not exists (
  select 1 from cte
  where id = t.id and created > t.created
)