From: | Vitaly Burovoy <vitaly(dot)burovoy(at)gmail(dot)com> |
---|---|
To: | Marc Mamin <M(dot)Mamin(at)intershop(dot)de> |
Cc: | Johannes <jotpe(at)posteo(dot)de>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: execute same query only one time? |
Date: | 2016-02-09 20:10:12 |
Message-ID: | CAKOSWNmv34UMQApv_w5RmgMrhUjCLJhU==koJk1A6j9XkegaOA@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 2/9/16, Marc Mamin <M(dot)Mamin(at)intershop(dot)de> wrote:
>
>>>>> Hi,
>>>>>
>>>>> is there a best practice to share data between two select statements?
>
> Hi,
> I didn't check the whole thread
Try it[1]. The thread is not so long (21 letters before yours) and it worth it.
> so forgive me if this was already proposed,
> but maybe you could do something like:
>
> create temp table result2 (...)
>
> query_1:
> WITH cte as (select ..),
> tmp as ( INSERT INTO result2 select ... from cte),
> SELECT ... from cte;
>
> query_2:
> select * from result2;
There is a mistake here: query2 returns the same result as the query_1.
>
> regards,
> Marc Mamin
It is similar to the fourth answer[2] in the thread.
If you are able to create temporary table with all fields of the first
result only for avoiding one statement, it can be rewritten without
CTE and one INNER JOIN (five statements):
BEGIN;
CREATE TEMPORARY TABLE temptable(id ..., col1 ..., col2 ..., ...) ON
COMMIT DROP;
INSERT INTO temptable
SELECT id, col1, col2, ...
FROM t0
WHERE col1 = value1 and col2 = value2 and ...
RETURNING *;
SELECT col1 FROM t1 INNER JOIN temptable ON (t0_id = temptable.id);
COMMIT;
===
If it is hard to detect (or just lazy to write) what types temporary
table has, you can rewrite it as (also five statements):
BEGIN;
CREATE TEMPORARY TABLE temptable ON COMMIT DROP AS
SELECT id, col1, col2, ...
FROM t0
WHERE id = (
SELECT max(id)
FROM t0
WHERE col1 = value1 and col2 = value2 and ...
);
SELECT * FROM temptable;
SELECT col1 FROM t1 INNER JOIN temptable ON (t0_id = temptable.id);
COMMIT;
===
But it is not so useful. In the case in original letter the best way
is to use only two queries and pass id from the result of the first
query as an argument to the second query. See the other letter[3] in
the thread.
Temporary tables are useful for keeping a lot of rows to prevent
copying them between client and server.
[1]http://www.postgresql.org/message-id/flat/56B8E6F9(dot)9070600(at)posteo(dot)de
[2]http://www.postgresql.org/message-id/CAKOSWNkRB0kfWHcw9CvOcRmkS8HuzrPVFLr0kKcjuYn6juK5NA@mail.gmail.com
[3]http://www.postgresql.org/message-id/CAKOSWN=wX9Myw4q9mpiqESyizU4tWrGivgbw+3Ef=5Q60viFSg@mail.gmail.com
--
Best regards,
Vitaly Burovoy
From | Date | Subject | |
---|---|---|---|
Next Message | Johannes | 2016-02-09 21:14:39 | Re: execute same query only one time? |
Previous Message | Marc Mamin | 2016-02-09 19:16:22 | Re: execute same query only one time? |