MYSQL更新最大时间戳的值

时间:2018-04-02 19:26:59

标签: mysql

我有这个问题:

  

从天气中选择* ICAO =' SSPB'和时间戳=   (从ICAO =' SSPB')的天气中选择最大(时间戳);

结果:

timestamp, ICAO, time, wind_angle, wind_speed, gust, visibility, condition, sky, temp, dew, pressure, humidity

2018-04-02 19:20:01, SSPB, 021919, 230, 03, , 9999, , SCT026, 23, 17, 1012, 67%

现在我想使用与select

相同的方法进行更新
  

更新天气设置wind_speed =' 10'其中ICAO =' SSPB'和   timestamp =(从天气中选择最大(时间戳)ICAO =' SSPB');

我收到此错误:

错误代码:1093。您无法指定目标表'天气'用于FROM子句

中的更新

2 个答案:

答案 0 :(得分:0)

您是衍生合并优化的受害者。但是,您可以通过创建临时表来避免使用另一个选择行。试试这个:

update weather set wind_speed = '10' where ICAO = 'SSPB' and timestamp =
( select c.cTime from 
      (select max(timestamp) as cTime 
       from weather where ICAO = 'SSPB'
       ) as c
);

答案 1 :(得分:0)

一种可能的解决方法是对内联视图(派生表)进行JOIN。我们可以使用SELECT声明......

来实现
SELECT t.*
  FROM weather t
  JOIN ( SELECT q.ICAO
              , MAX(q.timestamp) AS max_timestamp
           FROM weather q
          WHERE q.ICAO = 'SSPB'
          GROUP BY q.ICAO
       ) s
    ON t.ICAO      = s.ICAO
   AND t.timestamp = s.max_timestamp 
 WHERE t.ICAO = 'SSPB' 

同样的模式适用于UPDATE。我们可以将SELECT ... FROM替换为UPDATE并在SET子句之前添加WHERE子句,将SELECT语句转换为UPDATE:

 UPDATE weather t
  JOIN ( SELECT q.ICAO
              , MAX(q.timestamp) AS max_timestamp
           FROM weather q
          WHERE q.ICAO = 'SSPB'
          GROUP BY q.ICAO
       ) s
    ON t.ICAO      = s.ICAO
   AND t.timestamp = s.max_timestamp 
   SET t.wind_speed = '10'
 WHERE t.ICAO = 'SSPB'