title: SQL script behaves differently when run from PHP
body: <p>I have about 5 million records in a database table (MySQL 5.6), and I wanted to get the last 2 dates, grouped by ID. Looking around the web, I found examples that allowed me to cobble together the following...</p>
  <pre><code>SELECT id, date 
  FROM 
  (
      SELECT *,   
      @id_rank := IF(@current_id = id, @id_rank + 1, 1) AS id_rank,   
      @current_id := id 
      FROM `data` 
      ORDER BY id DESC, date DESC
  ) ranked 
  WHERE id_rank &lt;= 2 
  ORDER BY id ASC, date DESC
  </code></pre>
  <p>Running this code from MySQL Workbench, returned 5,700 rows, which is what I expected. I then tried to call this SQL as-is from PHP, using the following SQL string...</p>
  <pre><code>$subSql =
      &quot;SELECT *, &quot; .
      &quot;  @id_rank := IF(@current_id = id, @id_rank + 1, 1) AS id_rank, &quot; .
      &quot;  @current_id := id &quot; .
      &quot;FROM `data` &quot; .
      &quot;ORDER BY id DESC, date DESC&quot;;
  
  $sql =
      &quot;SELECT id, date &quot; .
      &quot;FROM ($subSql) ranked &quot; .
      &quot;WHERE id_rank &lt;= 2 &quot; .
      &quot;ORDER BY id ASC, date DESC&quot;;
  </code></pre>
  <p>However, running this code resulted in out-of-memory. I them modified the code to return a count of the number of records expected, and instead of the expected 5,700 rows, it returned 4,925,479. So my question is &quot;what do I have to change in my PHP SQL above, to get the correct results that I was getting from MySQL Workbench&quot;.</p>