我正在尝试将子查询的结果保存到表中。
select (b.close - a.close) AS difference from day_ohlcs AS a inner join day_ohlcs AS b ON a.id + 1 = b.id
子查询的速度很快,但是当我尝试将它放在更新语句中时,它需要永远,所以我知道我做错了。
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;
我不理解什么?提前谢谢。
答案 0 :(得分: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
答案 1 :(得分:0)
两个查询之间的语义非常不同。请注意,day_ohlcs出现两次而不是三次 - 后者会进行太多的计算,主要是计算整个表的差异。
您可以删除不需要的行为,如下所示:
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