如何使用subselect更新表

时间:2014-03-06 09:15:23

标签: mysql sql

我正在尝试将subselect的输出与更新表中的字段连接起来。但是使用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`;

1 个答案:

答案 0 :(得分: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

如果你在主表和x子查询之间有一个连接列,那么就像这样。