title: MySql query execution takes for ever from PHP but finishes soon when run from phpMyAdmin
body: <p>I have a sql querying a MySql table having millions of records. This gets executed in phpMyAdmin in around 2 secs but when run from PHP script, it doesn't complete executing.</p>
  
  <pre><code>select 
    concat(p1.`Date`," ",p1.`Time`) as har_date_from,
    concat(p2.`Date`," ",p2.`Time`) as har_date_to,
   (select concat(p3.`Date`," ",p3.`Time`) from 
     power_logger p3 
     where p3.slno between 1851219 and 2042099
     and p3.meter_id="logger1"
     and str_to_date(concat(p3.`Date`," ",p3.`Time`),"%d/%m/%Y %H:%i:%s") &gt;=
         str_to_date(concat(p1.`Date`," ",p1.`Time`),"%d/%m/%Y %H:%i:%s")
  
     order by p3.slno limit 1) as cur_date_from,
       (select concat(p4.`Date`," ",p4.`Time`) from
          power_logger p4 
          where p4.slno between 1851219 
          and 2042099
          and p4.meter_id="logger1" 
          and str_to_date(concat(p4.`Date`," ",p4.`Time`),"%d/%m/%Y %H:%i:%s") &gt;=
              str_to_date(concat(p2.`Date`," ",p2.`Time`),"%d/%m/%Y %H:%i:%s")
          order by p4.slno 
          limit 1
        )
        as cur_date_to, 
        p1.THD_A_N_Avg-p2.THD_A_N_Avg as thd_diff
        from power_logger p1
      join 
        power_logger p2 
          on p2.slno=p1.slno+1 
          and p1.meter_id="fluke1" 
          and p2.meter_id=p1.meter_id
          and p1.slno between 2058609 and 2062310 
          and p1.THD_A_N_Avg-p2.THD_A_N_Avg&gt;=2.0000
  </code></pre>
  
  <p>php script:
  <code>$query=/*The query above passed as string*/
  $mysql=mysql_connect('localhost','username','pwd') or die(mysql_error());
  mysql_select_db('dbname',$mysql);
  $rows=mysql_query($query,$mysql) or die(mysql_error());</code></p>
  
  <p>There are no issues in mysql connectivity and related stuffs, as I run a lot of other queries successfully. I have set indexes on meter_id and Date,Time together. slno is the auto increment value.
  I know there are similar questions asked as I found a lot from my research but none of them really helped me. Thanks in advance if anybody could help me out to find a solution.</p>
  
  <p>Query Description:This queries the power_logger table containing millions of records and THD_A_N_AVG, meter_id,slno,Date and Time are among the columns of the table. This selects The date and time from two consecutive rows with in a range of slnos where difference between THD_A_N_AVG is greater than or equal to 2. When those dates are fetched, it even has to fetch the date and time with in a different range of slnos where the date and time are the closest to the once fetched earlier thus forming har_date_from,har_date_to, cur_date_from,cur_date_to.
  What messes up here is the nested select. </p>