在不使用横向连接的情况下重写查询

时间:2016-10-01 20:33:36

标签: sql postgresql

有没有更简单的方法来表达下面的查询,而不使用横向连接(我的ORM不支持)?

select 
    v.id,
    v.name,
    v.avatar,
    sent_at,
    opened_at,
    replied_at
from visitors v
left join auto_message_events ame on ame.visitor_id = v.id
left join lateral (
    select inserted_at as sent_at from auto_message_events ame
    where ame.visitor_id = v.id and ame.event = 'sent'
) as sent on true
left join lateral (
    select inserted_at as opened_at from auto_message_events ame
    where ame.visitor_id = v.id and ame.event = 'opened'
) as opened on true
left join lateral (
    select inserted_at as replied_at from auto_message_events ame
    where ame.visitor_id = v.id and ame.event = 'replied'
) as replied on true
where ame.auto_message_id = 99
limit 10

1 个答案:

答案 0 :(得分:0)

一种方法是条件聚合:

select v.id, v.name, v.avatar,
       max(case when  ame.event = 'sent' then ame.inserted_at end) as sent_at,
       max(case when  ame.event = 'opened' then ame.inserted_at end) as opened_at,
       max(case when  ame.event = 'replied' then ame.inserted_at end) as replied_at
from visitors v join
     auto_message_events ame 
     on ame.visitor_id = v.id
where ame.auto_message_id = 99
group by v.id
limit 10;

我不确定是否确实需要where子句,因为它的目的可能是只返回原始表中每个访问者的一行。