From: | David Johnston <polobo(at)yahoo(dot)com> |
---|---|
To: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: Why does this array query fail? |
Date: | 2013-09-18 03:03:28 |
Message-ID: | 1379473408021-5771366.post@n5.nabble.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Ken Tanzer wrote
>
> SELECT client_id,
> COALESCE(
> (SELECT array_agg(code) FROM (
> SELECT distinct
> client_id,unnest(accessed_health_care_non_urgent_codes) AS code
> FROM service_reach
> WHERE client_id=client.client_id
> AND service_date BETWEEN '2013-08-01' AND '2013-08-31'
> ) foo
> ),array['(none)'])
> AS accessed_health_care_non_urgent_codes
> FROM client;
Equivalent semantics:
WITH clients_with_codes AS (
SELECT client_id, array_agg(code) AS client_codes FROM (SELECT client_id,
unnest(accessed...) AS code FROM service_reach) foo GROUP BY client_id
)
SELECT client_id, COALESCE(client_codes, ARRAY['(none)']) AS client_codes
FROM client LEFT JOIN client_with_codes USING (client_id)
Should (recommend testing) perform better due to the simple fact that you
avoid the correlated sub-query (i.e., a sub-query that references the outer
query to obtain some parameter - in this case the client_id of the current
row). The goal is to create an uncorrelated sub-query/relation that
contains all the data you require then JOIN it with the original outer
relation using the same equality you were using in the correlated version.
David J.
--
View this message in context: http://postgresql.1045698.n5.nabble.com/Why-does-this-array-query-fail-tp5771165p5771366.html
Sent from the PostgreSQL - general mailing list archive at Nabble.com.
From | Date | Subject | |
---|---|---|---|
Next Message | David Johnston | 2013-09-18 03:15:39 | Re: Why does this array query fail? |
Previous Message | Ken Tanzer | 2013-09-18 02:04:33 | Re: Why does this array query fail? |