使用select with join进行Mysql更新查询

时间:2012-06-06 10:46:06

标签: mysql join

我正在尝试使用select中运行mysql更新查询,但是我收到了一个错误。查询是这样的:

UPDATE keywords_stats_google_temp SET (Impressions_chg, Clicks_chg, AveragePosition_chg, Ctr_chg, AverageCpc_chg, CurrentMaxCpc_chg, FreeJoins_chg, PaidJoins_chg) = (SELECT 
                SUM(Impressions) AS Impressions,
                SUM(Clicks) AS Clicks,
                SUM(Impressions*AveragePosition)/SUM(Impressions) AS AveragePosition,
                (SUM(Clicks)*revenue_price)/SUM(Impressions) AS Ctr,
                SUM(Spend)/SUM(Clicks) AS AverageCpc,
                CurrentMaxCpc,
                SUM(free_joins) AS FreeJoins,
                SUM(paid_joins) AS PaidJoins
                FROM (SELECT KeywordId FROM keywords_stats_google_temp) a JOIN keywords_stats_google_naughtymeetings b ON b.KeywordId = a.KeywordId WHERE b.TimePeriod >= '2012-04-01 00:00:00'
                AND b.TimePeriod <= '2012-04-23 00:00:00' GROUP BY a.KeywordId, MatchType) 

但我只得到“#1064 - 您的SQL语法出错了;请查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法'(Impressions_chg,Clicks_chg,AveragePosition_chg,Ctr_chg,AverageCpc_chg ,Curr'在第1行“

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:8)

你不能在MySQL中拥有SET (a,b) = (value_a, value_b)

重写查询。像这样:

UPDATE 
    keywords_stats_google_temp AS u
  JOIN
    ( SELECT 
          SUM(Impressions) AS Impressions,
          SUM(Clicks) AS Clicks,
          SUM(Impressions*AveragePosition)/SUM(Impressions) AS AveragePosition,
          (SUM(Clicks)*revenue_price) / SUM(Impressions) AS Ctr,
          SUM(Spend)/SUM(Clicks) AS AverageCpc,
          CurrentMaxCpc,
          SUM(free_joins) AS FreeJoins,
          SUM(paid_joins) AS PaidJoins
      FROM keywords_stats_google_naughtymeetings AS b  
      WHERE b.TimePeriod >= '2012-04-01 00:00:00'
        AND b.TimePeriod <= '2012-04-23 00:00:00' 
      GROUP BY KeywordId, 
               MatchType
    ) AS tmp
        ON  tmp.KeywordId = u.KeywordId 
        AND tmp.MatchType = u.MatchType
SET 
  u.Impressions_chg     = tmp.Impressions, 
  u.Clicks_chg          = tmp.Clicks, 
  u.AveragePosition_chg = tmp.AveragePosition, 
  u.Ctr_chg             = tmp.Ctr,
  u.AverageCpc_chg      = tmp.AverageCpc, 
  u.CurrentMaxCpc_chg   = tmp.CurrentMaxCpc, 
  u.FreeJoins_chg       = tmp.FreeJoins, 
  u.PaidJoins_chg       = tmp.PaidJoins ;