3

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

产品表定义为

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;
4

2 回答 2

2

使用CTE可能会更快。
不确定,这取决于。检查与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;
于 2012-12-19T04:23:22.743 回答
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)

该查询应该给出围绕“奶酪”的 40 条记录

于 2012-12-18T16:24:55.297 回答