在主键字段选择具有最大值的行的最快方法

时间:2014-10-22 09:08:27

标签: sql performance postgresql greatest-n-per-group

我有一张桌子:

CREATE TABLE spots(
    datetime TIMESTAMP,
    market VARCHAR(15),
    spot NUMERIC(10, 5),
    PRIMARY KEY (market, datetime)
);

我需要选择p_market的行,其最大值为datetime,该值小于或等于p_datetime,因此我有两个选项:

SELECT * FROM spots WHERE market = p_market AND datetime = (
    SELECT MAX(datetime) FROM spots WHERE market = p_market AND datetime <= p_datetime
);

SELECT * FROM spots WHERE market = p_market AND datetime <= p_datetime
ORDER BY datetime DESCENDING LIMIT 1;

所以,问题是 - 从绩效角度来看,哪种变体更好。

1 个答案:

答案 0 :(得分:0)

Postgres支持window function,理论上应该在处理行时逐步计算,因此它应该会对大型数据集提供一些性能提升:

SELECT * 
FROM   (SELECT *,
               RANK() OVER (ORDER BY datetime DESC) AS rk
        FROM   spots
        WHERE  market = p_market AND datetime <= p_datetime) t
FROM   spots 
WHERE  rk = 1