您不需要子查询。使用
window functions
在这种情况下效率更高。现在大多数数据库都支持窗口函数/分析函数。
另外,假设您正在搜索给定列表的订单,而不是表中的订单列表,请尝试下面的示例查询。这里,“test”表包含您的订单事务记录,数组将包含您试图查找的订单列表。必须使用UNNEST函数将数组转换为行,然后找出测试表中不存在的顺序id。如果可以在另一个表中找到要查找的订单列表,则可以以不同的方式编写查询。
WITH
dataset AS (
SELECT ARRAY[1,2,3,4,5] AS items
)
select order_id, status, order_time from
(
select order_id, status, order_time, row_number() over (partition by order_id order by order_time ) rn
from test
union all
select orders, null, null, 1 from dataset
cross join unnest(items) as t(orders) where orders not in (
select order_id from test
)
)
where rn = 1