将限制和偏移量添加到使用分区的oracle查询

时间:2012-03-19 09:48:08

标签: sql oracle

  

可能重复:
  How do I limit the number of rows returned by an oracle query?

我在oracle中有这个查询,它通过一些元数据和线程讨论获得了数据库中的所有讨论。我想在查询中添加限制和偏移量,如何更改它以支持它。

SELECT * FROM
                (SELECT discussions.created_at, discussions.id, discussions.title, discussions.stub,
                users.username AS created_by, 
                count(distinct threads.id) over (partition by discussions.created_at, 
                                                  discussions.title, 
                                                  users.username) AS replies, 
                count(distinct discussion_views.discussion_id) 
                    over (partition by discussions.created_at, 
                            discussions.title, 
                            users.username) AS views,
                latest_poster.username AS latest_post_by,
                threads.updated_at AS latest_post_at,
                row_number() over (partition by discussions.created_at, 
                                    discussions.title, 
                                    users.username
                       order by threads.id desc) AS rn
            FROM discussions
            LEFT JOIN threads on discussions.id=threads.discussion_id
            LEFT JOIN discussion_views on discussions.id=discussion_views.discussion_id
            JOIN users on users.id=discussions.user_id
            JOIN users latest_poster ON (latest_poster.id=threads.user_id)
            WHERE discussions.course_id={$course_id}
            ) sq
            WHERE rn=1
            ORDER BY created_at desc"

1 个答案:

答案 0 :(得分:1)

SELECT
  *
FROM
(
  SELECT
    rownum AS row_id,
    <your other selects>
  FROM
    <your query>
  ORDER BY
    <whatever>
)
  data
WHERE
      data.row_id >= 123
  AND data.row_id <= 222