【问题标题】:Selecting All Rows Matching Matching First 10 IDs in Oracle在 Oracle 中选择匹配前 10 个 ID 的所有行
【发布时间】:2020-03-20 14:28:07
【问题描述】:

这是 Oracle 中与分页相关的问题。我有两个表,LIST 和 LIST_ITEM 具有一对多的关系。我正在尝试对列表数量实现分页,其中每个 LIST 可以包含可变数量的 LIST_ITEM。本质上,我需要从 LIST_ITEM 中获取与前 N 个 LIST id 匹配的所有行。关于在 Oracle DB 中实现这一点的任何想法?理想情况下不添加单独的查询。

以前我使用 JPA EntityManager 通过 setFirstResult() 和 setMaxResults() 来实现分页,但是因为这个查询应该返回的行数是可变的,所以这对我来说不再适用了。

【问题讨论】:

  • 具有预期输出的示例查询会有所帮助。

标签: sql database oracle


【解决方案1】:

您可以在子查询中使用analytic function 之类的dense_rank() 对ID 进行排名,然后根据您想要的排名进行过滤,例如:

select id, col1, col2
from (
  select id, col1, col2, dense_rank() over (order by id) as rnk
  from list_items
)
where rnk <= 10

或用于以后的页面

select id, col1, col2
from (
  select id, col1, col2, dense_rank() over (order by id) as rnk
  from list_items
)
where rnk > 10 and <= 20

如果列表中的 ID 没有 ID,并且您希望将其考虑在内,则可以对该表使用子查询并连接(这也允许您包含其他列表列):

select l.id, li.col1, li.col2
from (
  select id, dense_rank() over (order by id) as rnk
  from list
) l
left join list_items li on li.id = l.id
where l.rnk <= 10;

如果您使用的是 Oracle 12c 或更高版本,则可以使用 [行限制子句] 增强功能来简化:

select l.id, li.col1, li.col2
from (
  select id
  from list
  order by id
  fetch next 10 rows only
) l
left join list_items li on li.id = l.id;

或第二页:

  offset 10 rows fetch next 10 rows only

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多