我有一张桌子:
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;
所以,问题是 - 从绩效角度来看,哪种变体更好。
答案 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