應該是最簡單的&與LEFT JOIN
和DISTINCT ON
最快:
WITH x(search_ts) AS (
VALUES
('2012-07-26 20:31:29'::timestamp) -- search timestamps
,('2012-05-14 19:38:21')
,('2012-05-13 22:24:10')
)
SELECT DISTINCT ON (x.search_ts)
x.search_ts, r.id, r.resulttime
FROM x
LEFT JOIN results r ON r.resulttime <= x.search_ts -- smaller or same
-- WHERE some_id = 15 -- some condition?
ORDER BY x.search_ts, r.resulttime DESC;
結果(虛設的值):
search_ts | id | resulttime
--------------------+--------+----------------
2012-05-13 22:24:10 | 404643 | 2012-05-13 22:24:10
2012-05-14 19:38:21 | 404643 | 2012-05-13 22:24:10
2012-07-26 20:31:29 | 219822 | 2012-07-25 19:47:44
我使用CTE提供的值,可能是一個表或函數或嵌套的陣列或與generate_series()
別的東西以及生成一組。 (您的意思是generate_series()
通過「generate_sequence()」?)
首先我JOIN
搜索時間戳到表中的所有行與早期或等於resulttime
。我使用LEFT JOIN
而不是JOIN
,這樣當表中根本沒有以前的resulttime
時,搜索時間戳不會丟失。
隨着DISTINCT ON (x.search_ts)
與ORDER BY x.search_ts, r.resulttime DESC
的組合,我們得到的最小(或最大的一個)resulttime
小於或等於每個搜索時間戳。
什麼是您的數據類型 - 「日期」或「時間戳」?準確定義「最接近」。你如何提供這一系列的日子?作爲表中的日期,每行一個日期? – 2012-07-26 13:41:05
他們是類型的時間戳。 「最近的記錄優先」被定義爲在給定日期之前的第一個記錄。這可能包括前一天的記錄。 – root 2012-07-26 17:36:00