2012-01-31 33 views
2

我試圖更新一個包含股票定價信息的表格,以包含這些股票在不同時間段的回報。回報是在時間段開始時插入的。 下面的SELECT語句計算我正在查找的值爲3個月和6個月的保留期間。該表是price_returns將使用OUTER JOIN的mysql轉換爲UPDATE

SELECT 
     curr.date, curr.company, curr.price, 
     (mo3.price - curr.price)/curr.price AS 3MONTH_RETURN, 
     (mo6.price - curr.price)/curr.price AS 6MONTH_RETURN 
FROM 
    price_returns AS curr 
LEFT OUTER JOIN 
     price_returns AS mo3 
    ON 
     ((curr.date = LAST_DAY(mo3.date - INTERVAL 3 MONTH)) AND (curr.company = mo3.company)) 
LEFT OUTER JOIN 
     price_returns AS mo6 
    ON 
     ((curr.date = LAST_DAY(mo6.date - INTERVAL 6 MONTH)) AND (curr.company = mo6.company)) 
Order by 
     curr.company, curr.date; 

我想轉換此SELECTUPDATE到表price_returns並插入3MONTH_RETURN6MONTH_RETURN爲列ret_3mthret_6mth

這是我的,但它沒有正確執行更新。聯接似乎正在工作,因爲它與正確的行數匹配,但不會更改任何行。

*更新*

不知道爲什麼,但低於現在這個代碼,似乎是工作。對困惑感到抱歉。我仍然沒有弄清楚發生了什麼,爲什麼它不是,但現在正在工作。用戶錯誤我確定。

*更新*

UPDATE 
     price_returns AS curr 
LEFT OUTER JOIN 
     price_returns AS mo3 
    ON 
     ((curr.date = LAST_DAY(mo3.date - INTERVAL 3 MONTH)) AND (curr.company = mo3.company)) 
LEFT OUTER JOIN 
     price_returns AS mo6  
    ON 
     ((curr.date = LAST_DAY(mo6.date - INTERVAL 6 MONTH)) AND (curr.company = mo6.company)) 
SET 
     curr.ret_3mth = (mo3.price - curr.price)/curr.price, 
     curr.ret_6mth = (mo6.price - curr.price)/curr.price; 

感謝您的幫助。

回答

2

您可以在此使用子查詢(http://dev.mysql.com/doc/refman/5.0/en/subqueries.html)

UPDATE price_returns SET curr.ret_3mth = (SELECT (mo3.price - curr.price)/curr.price in here with the join), 
curr.ret_6mth = (Select (mo6.price - curr.price)/curr.price in here with the join) 

所以在括號中有子查詢做,在那裏你會通過上面選擇的代碼(第一個mysql代碼是)

+0

感謝您的幫助,很高興看到另一種方式。我剛剛嘗試了原始代碼,現在它正在工作。不知道我在其他時候做了什麼錯了。感謝您的幫助,非常感謝。 – 2012-01-31 01:58:33