我只想从另一个子查询结果中包含的表中 Select 那些标识符,并且只能使用前2行.
例如,您可以在PG上运行查询:
select a.rid
from(
values (41), (42), (43), (44)
) a(rid)
where a.rid in
(
select b.x
from(
values (43), (44), (42), (41)
) b(x)
order by b.x
fetch first 2 rows only
);
它应该返回
41
42
有时灵然而,如果我使用以下查询来处理CTE
select rid
from(
values (41), (42), (43), (44)
) s(rid)
where rid in
(
with recursive messages as (
select
rid as "root_id",
parent.id,
parent.sent_date
from
purchase_message parent
where
parent.id = rid
union
select
rid as "root_id",
child.id,
child.sent_date
from
purchase_message child
join messages on
child.parent_message_id = messages.id
),
ordered_root_ids as (
select
m."root_id",
max(m."sent_date") over (partition by m."root_id") as "maxSentDate"
from
messages m
order by "maxSentDate" desc
)
select "root_id" from ordered_root_ids
fetch first 2 rows only
)
它不起作用.我得到所有结果
41, 42, 43, 44
为什么它不只返回2个结果? 根据我的预期,它必须只有2个结果,而且必须是43和44,因为它们是最新的消息.
我不知道如何提供所有相关表,因为太多了.我希望它们没有必要.CTE、循环CTE或嵌套查询是否会影响这一点?或者所有这些的组合?如何修改上述查询,使其对子查询中的数据进行排序,取顶部2行,然后将它们用于外部查询的in
分句?