2013-10-14 243 views
0

我想將子查詢的結果保存到表中。如何用子查詢更新多行?

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

嗯,你做一個特里普爾加入此表。如果它很大,這可能會影響性能。 – bksi

+0

我只想從一行到另一行的一列的差異。我應該試圖實現一個窗口函數嗎? – Bijan

回答

0

語義有很大的不同兩次查詢之間。請注意,day_ohlcs出現兩次vs三次 - 後者進行了大量計算,實質上計算了整個表的差異。

您可以刪除不需要的行爲,像這樣:

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

+0

如何設置A的訂單?我把它與表b一起工作,但我怎麼能用A來完成? – Bijan

+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