是否可以在选择中使用非标量相关子查询?类似于generate_series如何在select?
中使用非标量我的意思是返回超过1行(此刻并不真正关注列):
select
o1.user_id,
o1.order_id,
o1.order_date,
(select
o2.order_id
from orders o2
where o2.user_id = o1.user_id
and o2.order_date < o1.order_date
order by o2.order_date desc
limit 2) as last_2_orders
from orders o1
有人告诉我,任何可以表示为横向连接的东西都可以表示为相关子查询。所以我试图找到一个可以表达以下内容的相关子查询:
select
o1.user_id,
o1.order_id,
o1.order_date,
o3.last_2_orders
from orders o1
left join lateral (
select
o2.order_id as last_2_orders
from orders o2
where o2.user_id = o1.user_id
and o2.order_date < o1.order_date
order by o2.order_date desc
limit 2
) as o3 on true
编辑:此类作品但不符合左外部要求:
select
o1.user_id,
o1.order_id,
o1.order_date,
unnest(
array(
select o2.order_id
from orders o2
where o2.user_id = o1.user_id
and o2.order_date < o1.order_date
order by o2.order_date desc
limit 2
)
) as last_2_orders
from orders o1