Join tables using the closest datetime values

From: "Anton Krokovny" <kronya(at)mail(dot)ru>
To: pgsql-general(at)postgresql(dot)org
Subject: Join tables using the closest datetime values
Date: 2006-02-16 04:59:18
Message-ID: dt10r6$2m5$1@news.hub.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hello,

I have two tables with same structure:

CREATE TABLE k1 (
begintime timestamp with time zone NOT NULL,
rowid serial NOT NULL
);
ALTER TABLE ONLY k1
ADD CONSTRAINT k1_time_key PRIMARY KEY (begintime);

They contain a huge number of data (about 100000-200000 records).
I need to join these tables on begintime column, but in most cases there are
no equal timestamps in each other. That's why I need to choose the closest
timestamp from another table.

At this moment I'm using the following implementation (sorting and taking
first above):

CREATE OR REPLACE FUNCTION test(x timestamp with time zone, OUT y int) AS
'SELECT rowid FROM k2 WHERE begintime <= $1 ORDER BY begintime DESC
LIMIT 1'
language SQL;

SELECT rowid, test(begintime) FROM k1;

This algorithm takes about 5 seconds for executing (excluding data
fetching).

Is there any solution faster than the current one?

Anton.

Browse pgsql-general by date

  From Date Subject
Next Message Chris 2006-02-16 05:07:38 Re: Oracle purchases Sleepycat - is this the "other shoe"
Previous Message Tom Lane 2006-02-16 04:38:47 Re: Oracle purchases Sleepycat - is this the "other shoe"