title: Query to select latest record when using Group By - MySQL
body: <p>There is a table structure:</p>
  
  <pre><code>ID1 (int), ID2 (int), AddedAt (datetime)
  </code></pre>
  
  <p>where <strong>ID1</strong> and <strong>ID2</strong> are primary keys. Now This table contains already up to <strong>300,000</strong> records and I need to restructure the table to have <strong>1-1</strong> relationship. Meaning i need to drop the <strong>ID1</strong> from being primary key and make only ID2 to be the primary key but there are records that already contain multiple <strong>ID2s</strong> for each <strong>ID1</strong>.</p>
  
  <p>Now before i do that I need to have a query to select all the records where multiple <strong>ID2</strong> exists and remove them, only need to leave one record ID2 and that record has to be latest one which is determined by <strong>AddedAt datetime</strong> column.</p>
  
  <p>This is what i have so far:</p>
  
  <pre><code> SELECT *, COUNT(*) AS Total
   FROM TestTable
   GROUP BY ID2
   HAVING Total &gt; 1
  </code></pre>
  
  <p>this successfully returns all records but <strong>AddedBy</strong> does not come out to be the latest one. What do i need to add to this query to get the latest record only 1 for Grouped By ID2 so that i can make the ID2 to be the primary key.</p>
  
  <p>If this cant be done in MySQL can it be done in PHP?</p>