Re: how to remove a for-loop from programming language and put it into the query?

From: Sim Zacks <sim(at)compulab(dot)co(dot)il>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: how to remove a for-loop from programming language and put it into the query?
Date: 2010-07-06 05:39:15
Message-ID: 4C32C183.2060809@compulab.co.il
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


> (external programming language)
> for ($i = 1; $i < 500; $i++) {
> // return me the "most recent" diag_value from a hardware_id $i
> // at the desired timestamp
> runquery("select diag_value from diagnose_logs where ts <= '2009-12-25
> 23:59:59' and hardware_id = $i order by ts desc limit 1");
> }
>
> can I turn this for-loop into a single query to run in postgres?
>
> Thanks,
> Pedro
>
Try:

SELECT diag_value FROM diagnose_logs a where id in
(
SELECT id FROM diagnose_logs b
WHERE a.hardware_id=b.hardware_id
and ts <= '2009-12-25 23:59:59'
and hardware_id between 1 and 500
ORDER BY ts LIMIT 1)
ORDER BY hardware_id;

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Luca Ferrari 2010-07-06 06:53:03 TupleDesc and HeapTuple
Previous Message Alan Corey 2010-07-06 04:59:49 cgi program doing multiple queries hangs in multiple places