在Postgresql中选择最近记录的更好方法

时间:2012-12-18 15:40:50

标签: sql postgresql

从表中选择上一个和下一个记录的最佳方法是允许用户查看给定产品名称的最近产品,e.q Cheese

产品表定义为

create table toode (
  toode char(20) primary key, -- product code
  name char (100)    -- product name
  ) 

下面的代码似乎有效,但看起来有点难看。哪个是在Postgres中实现这个的最好方法?

CREATE temp table toodevalik1 on commit drop as 
SELECT * 
FROM toode 
WHERE name  >= 'Cheese'
order by name, toode
limit 50;

CREATE temp table toodevalik2 on commit drop as 
SELECT * 
FROM toode 
WHERE name  < 'Cheese'
order by name desc, toode desc
limit 50;

SELECT * 
FROM toodevalik1
union all
SELECT * 
FROM toodevalik2
order by name, toode;

2 个答案:

答案 0 :(得分:2)

使用CTEs可能会更快 不确定,这取决于。请查看EXPLAIN ANALYZE

WITH x AS (
    SELECT *, row_number() OVER (ORDER BY name, toode) AS rn
    FROM   toode
    )
, y AS (
    SELECT COALESCE(
          (SELECT rn FROM x WHERE fest >= 'Cheese' ORDER BY name, toode LIMIT 1)
         ,(SELECT max(rn) FROM x) -- fallback for value > all
        ) AS rn_mid
    )
SELECT *
FROM   x, y -- cross join ok, 1 row from y if any rows exist.
WHERE  x.rn BETWEEN y.rn_mid - 50 AND y.rn_mid + 50 
ORDER  BY rn;

答案 1 :(得分:1)

(select name from toode where name > 'Cheese' order by name limit 20)
union all
(select name from toode where name < 'Cheese' order by name desc limit 20)

该查询应该提供围绕'Cheese'的40条记录