2014-03-06 75 views
0

我試圖從更新表中的字段加入子查詢的輸出。但使用MySQL無法正確使用它。如何使用子選擇更新表

任何想法如何正確地做到這一點?

update INSTRUMENTDAILYINFO info 
set 
    info.vWap = (SELECT 
      t1.vWap 
     FROM 
      INSTRUMENTDAY t1 
       JOIN 
      (SELECT 
       Date(tradedate) date_date, 
        stockName, 
        min(tradedate) min_date 
      FROM 
       INSTRUMENTDAY 
      GROUP BY date_date , stockName) t2 ON t1.tradedate = t2.min_date 
       AND t1.stockName = t2.stockName 
     order by t1.tradedate , t1.stockName asc) 
where 
    t1.tradeDate = info.tradeDate 
     and t1.stockName = info.stockName 

SELECT 
`INSTRUMENTDAILYINFO`.`ID`, 
`INSTRUMENTDAILYINFO`.`CLOSEPRICE`, 
`INSTRUMENTDAILYINFO`.`HIGHVALUE`, 
`INSTRUMENTDAILYINFO`.`LOWVALUE`, 
`INSTRUMENTDAILYINFO`.`STARTPRICE`, 
`INSTRUMENTDAILYINFO`.`STOCKNAME`, 
`INSTRUMENTDAILYINFO`.`TRADEDATE` 
FROM `INSTRUMENTDAILYINFO`; 

SELECT 
`INSTRUMENTDAY`.`ID`, 
`INSTRUMENTDAY`.`STOCKNAME`, 
`INSTRUMENTDAY`.`TRADEDATE`, 
`INSTRUMENTDAY`.`VWAP` 
FROM `SimpleGrowth`.`INSTRUMENTDAY`; 
+0

你可以創建一個小提琴嗎? – Mihai

回答

1
UPDATE INSTRUMENTDAILYINFO info 
JOIN 
(SELECT t1.vWap,t1.tradedate as tradedate,t2.stockName as stockName 
    FROM INSTRUMENTDAY t1 
      JOIN 
      (SELECT 
       Date(tradedate) date_date, 
        stockName, 
        min(tradedate) min_date 
      FROM 
       INSTRUMENTDAY 
      GROUP BY date_date , stockName) t2 ON t1.tradedate = t2.min_date 
       AND t1.stockName = t2.stockName 
      ORDER BY t1.tradedate , t1.stockName asc)x 
ON 
    x.tradeDate = info.tradeDate 
AND x.stockName = info.stockName 
SET info.vWap= x.vWap 

事情是這樣的,如果你有主表和×副查詢之間的連接柱。

+0

someCommonColumn引用tradeDate和stockName是什麼?運行查詢時,我得到0行更新。 – user2130951

+0

@ user2130951顯示錶結構,INSTRUMENTDAILYINFO和INSTRUMENTDAY - 在那裏使用連接2個應用程序的外鍵列。 – Mihai

+0

優秀!保存此查詢。因爲一個表格字段是Timestamp而另一個日期ON則工作,如果DATE(x.tradeDate)= info.tradeDate – user2130951