Querying with arrays

From: Tim Dudgeon <tdudgeon(dot)ml(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Querying with arrays
Date: 2014-11-27 13:09:59
Message-ID: 547722A7.4040702@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I'm considering using arrays to handle managing "lists" of rows (I know
this may not be the best approach, but bear with me).

I create a table for my lists like this:**

create table lists (
id SERIAL PRIMARY KEY,
hits INTEGER[] NOT NULL
);

Then I can insert the results of a query into that table as a new list
of hits

INSERT INTO lists (hits)
SELECT array_agg(id)
FROM some_table
WHERE ...;

Now the problem part. How to best use that array of primary key values
to restore the data at a later stage. Conceptually I'm wanting this:

SELECT * from some_table
WHERE id <is in the list of ids in the array in the lists table>;

These both work by are really slow:

SELECT t1.*
FROM some_table t1
WHERE t1.id IN (SELECT unnest(hits) from lists WHERE id = 2);

SELECT t1.*
FROM some_table t1
JOIN lists l ON t1.id = any(l.hits)
WHERE l.id = 2;

Is there an efficient way to do this, or is this a dead end?

Thanks
Tim

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2014-11-27 14:54:30 Re: Querying with arrays
Previous Message Ron256 2014-11-26 19:51:16 Re: generating the average 6 months spend excluding first orders