如何通过sql选择first,last和previous和next

时间:2012-11-29 11:53:11

标签: sql sql-server

我正在尝试从sql语句创建记录的分页,我能够获得所有的下一个和上一个但是最后一条记录显示前一条记录为next,因为sql查询只返回1行而不是2。我根据第一个结果设置下一个,然后是第二个结果。

数据:

  • 苹果
  • 香蕉
  • 葡萄

sql:

select * 
from (select top 1 fruit 
      FROM table 
      where fruit > 'Banana' 
      order by fruit asc) as x 

UNION ALL 

select * 
from (select top 1 fruit 
      FROM table 
      where fruit < 'Banana' order by fruit desc) as y

结果:

fruit
--------
Grape
Apple

这很棒!

对于第一条记录 - 我得到第一条记录的正确结果是真正的下一条记录。 对于最后一条记录 - 我得到一个结果,这是获得前一条记录的第二个查询。但是我无法知道它的最后一条记录,所以它输出为Next而不是Previous。

我如何确定这是最后一条记录,并且返回的单行实际上是前一条记录?

OR

如何让查询为Next查询返回NULL行?所以我可以测试一个NULL结果吗?

奖励积分!

我怎么能有一个查询能够给我第一个记录,最后一个记录以及下一个和之前的记录,所以我可以启用循环分页?如果在第一个记录显示上一个记录。如果在最后一条记录中显示下一条记录为第一条记录?

1 个答案:

答案 0 :(得分:3)

SELECT
  *
FROM
(
  SELECT
    MIN(fruit)   as first,
    MAX(fruit)   as previous
  FROM
    yourTable
  WHERE
    fruit < 'banana'
)
CROSS JOIN
(
  SELECT
    MIN(fruit)   as next,
    MAX(fruit)   as last
  FROM
    yourTable
  WHERE
    fruit > 'banana'
)

或者,更短,但我不确定它会更高效......

SELECT
  MIN(CASE WHEN fruit < 'banana' THEN fruit END)   as first,
  MAX(CASE WHEN fruit < 'banana' THEN fruit END)   as previous,
  MIN(CASE WHEN fruit > 'banana' THEN fruit END)   as next,
  MAX(CASE WHEN fruit > 'banana' THEN fruit END)   as last
FROM
  yourTable

或者,作为最后一个奇怪的选择...

SELECT
  (SELECT TOP 1 fruit FROM yourTable WHERE fruit < 'banana' ORDER by fruit ASC)  AS first,
  (SELECT TOP 1 fruit FROM yourTable WHERE fruit < 'banana' ORDER by fruit DESC) AS previous,
  (SELECT TOP 1 fruit FROM yourTable WHERE fruit > 'banana' ORDER by fruit ASC)  AS next,
  (SELECT TOP 1 fruit FROM yourTable WHERE fruit > 'banana' ORDER by fruit DESC) AS last

(如果您有数千条记录,这可能很有用,因为每条记录都可以快速分开搜索。)