Does MySQL cache queries?
This is likely an artifact of the MySQL Query Cache.

You execute the SQL query, MySQL caches its result and the next execution if fast. When you run the script to insert the data in tables referenced by your query, the result cache gets invalidated and the query must be executed "for real" the next time.

From the MySQL documentation linked above:


  A query mix consisting almost entirely of a fixed set of SELECT
  statements is much more likely to benefit from enabling the cache than
  a mix in which frequent INSERT statements cause continual invalidation
  of results in the cache.