在PHP中执行时,LEFT JOIN非常慢

时间:2015-02-26 01:24:24

标签: php mysql left-join

我已经面临这个问题几天了,我不知道该怎么做,当我在mysql中执行这个查询需要大约8秒时间:

CREATE TEMPORARY TABLE temp_forecast AS 
   (SELECT gfs.spot, wind, winddir, clouds, temperature, gust,
           precipitation, pressure, humidity, wavedir, waveperiod,
           waveheight, gfs.hour, gfs.UTCdate, localdate, modelcicle, 
           tide, sst  
     FROM table1 AS gfs 
       left outer join table2 AS waves 
         on gfs.spot=waves.spot AND gfs.utcdate=waves.utcdate)

我执行了关于这个查询的解释并且索引没问题,它说它只需要在wave表格中检查一行gfs中的一行,但是当我在PHP中执行它时,最多可能需要20分钟来重载服务器,我不知道发生了什么

我在mysql中执行查询之前尝试了RESET QUERY CACHE;,看它是否被缓存但仍需要8秒,看起来查询在PHP中执行时没有使用索引,查询执行正确插入后,索引可能尚未就绪?

这是在PHP上执行查询的代码:

public function dumpData(Logger $log){
        $q['sql'] = sprintf("CREATE TEMPORARY TABLE temp_forecast AS (SELECT gfs.spot, wind, winddir, clouds, temperature, gust, precipitation, pressure, humidity, wavedir, waveperiod,
        waveheight, gfs.hour, gfs.UTCdate, localdate, modelcicle, tide, sst  FROM %s AS gfs left outer join %s AS waves on 
        gfs.spot=waves.spot AND gfs.utcdate=waves.utcdate", 
                    $this->GFSforecast,
                    $this->wavesForecast);
        $q['ret'] = 'row_count'; 
        $this->pdo->smartQuery($q, __FUNCTION__);
        $q['sql'] = sprintf("TRUNCATE TABLE %s", $this->forecast);
        $q['ret'] = 'row_count'; 
        $this->pdo->smartQuery($q, __FUNCTION__);
        $q['sql'] = sprintf("INSERT INTO %s (SELECT * FROM temp_forecast)", $this->forecast);
        $q['ret'] = 'row_count';            
        return $this->pdo->smartQuery($q, __FUNCTION__);
}

1 个答案:

答案 0 :(得分:1)

waves上,使用化合物INDEX(spot,utcdate)

如果这还没有解决,请告诉我们SHOW CREATE TABLE并告诉我们每张桌子有多大。

重新填充表格的更好方法是

  1. CREATE TABLE新LIKE预测;
  2. INSERT INTO new SELECT ...;
  3. RENAME TABLE预测TO旧,新TO预测;
  4. DROP TABLE old;
  5. 你永远不会没有表预测; RENAME是原子的,并且是瞬间的'。因此,即使SELECT(步骤2)很慢,也不会造成伤害(除了延迟更新)。