0

I am trying to save the results of a subquery into a table.

select (b.close - a.close) AS difference from day_ohlcs AS a inner join day_ohlcs AS b ON a.id + 1 = b.id

The speed of the subquery is fast, but when I try to put it in an update statement it takes forever, so I know I'm doing something wrong.

UPDATE day_ohlcs
SET price_change = t.difference
FROM (select (b.close - a.close) AS difference
    FROM day_ohlcs AS a 
    inner join day_ohlcs AS b 
    ON a.id + 1 = b.id) 
AS t
WHERE day_ohlcs.instrument_id = 1;

What am I not understanding? Thanks in advance.

4

2 回答 2

0

我认为那是因为您没有指定day_ohlcs要加入的列,例如:

UPDATE day_ohlcs
SET price_change = t.difference
FROM (select a.id, (b.close - a.close) AS difference
    FROM day_ohlcs AS a 
    inner join day_ohlcs AS b 
    ON a.id + 1 = b.id) 
AS t
WHERE day_ohlcs.instrument_id = 1 and day_ohlcs = t.id

实际上看起来你可以在没有子查询的情况下做到这一点

update day_ohlcs as a set
   price_change = b.close - a.close
from day_ohlcs as b 
where b.id = a.id + 1 and a.instrument_id = 1
于 2013-10-14T19:41:30.120 回答
0

The semantics are very different between the two queries. Note that day_ohlcs appears twice vs three times -- the latter does a great deal too many calculations, essentially calculating the difference for the entire table.

You can remove the unneeded behavior like so:

UPDATE day_ohlcs as a
SET price_change = b.close - a.close
FROM day_ohlcs AS b
WHERE a.id + 1 = b.id and a.instrument_id = 1;

http://www.postgresql.org/docs/current/static/sql-update.html

于 2013-10-14T19:44:14.330 回答