将重新移动平均值select语句重构为更新语句

时间:2018-02-24 14:10:57

标签: mysql

我有一个工作选择语句,它选择1day_rank的移动平均值

SELECT
 *, 
 (SELECT AVG(1day_rank)
  FROM keyword_rank T2
  WHERE (
           SELECT COUNT(*)
           FROM keyword_rank T3
           WHERE timestamp BETWEEN T2.timestamp AND T1.timestamp and t3.keyword_id=t2.keyword_id 
      ) BETWEEN 1 AND 7 and T2.keyword_id=T1.keyword_id and (T2.timestamp > T1.timestamp - interval 7 day)
 ) average
FROM keyword_rank T1 where T1.keyword_id=86;

我想将此语句重构为更新语句,该语句将结果更新为7day_rank。但MY_SQL不允许这样做:“错误代码:1093:您无法在FROM子句中为更新指定目标表'T1'”

update keyword_rank T1 set T1.7day_rank=
 (
 SELECT
      AVG(1day_rank)
 FROM
      (select * from keyword_rank sub where sub.keyword_id=86) as T2
 WHERE
      (
           SELECT
                COUNT(*)
           FROM
                keyword_rank T3
           WHERE
                timestamp BETWEEN T2.timestamp AND T1.timestamp and t3.keyword_id=86 
      ) BETWEEN 1 AND 7 and (T2.timestamp > T1.timestamp - interval 7 day)
 )
  where T1.keyword_id=86;

所以我试图使用内部联接重构此语句但是会在“where子句”中创建另一个错误“错误代码:1054,未知列'T1.timestamp'”

update keyword_rank T1 inner join (
  select AVG(1day_rank) average, timestamp from keyword_rank T2
  where (
           SELECT COUNT(*)
           FROM keyword_rank T3
           WHERE timestamp BETWEEN T2.timestamp AND T1.timestamp and t3.keyword_id=86 
      ) BETWEEN 1 AND 7 and T2.keyword_id=86 and (T2.timestamp >   T1.timestamp - interval 7 day)
 ) as TX set T1.7day_rank=TX.average;

1 个答案:

答案 0 :(得分:1)

我能够通过整个工作选择并将其放入内连接来修复查询。

x