I am trying the get the last entry from the table group by type.
I tried to use sub select method but it was not working.
Please help how I achieve the goal
and get the expected output.
The sub-query needs to be the rest of that query. You are trying to get the maximum id per GROUP. You also need to use WHERE ID IN(…), because the sub-query will return a set of ids, one per group.
I did a little test script on my local server and this seems to work doing it this way?
// The SQL statement selects all columns from rows in the FruitTable where
// each row has the maximum ID for its type and the key equals 'AP123'.
$sql = "SELECT t1.*
FROM FruitTable t1
JOIN (
SELECT type, MAX(ID) as maxID
FROM FruitTable
WHERE `key` = :key
GROUP BY type
) t2
ON t1.type = t2.type AND t1.ID = t2.maxID ORDER BY ID";
$stmt = $pdo->prepare($sql);
$stmt->execute(['key' => 'AP123']);
$data = $stmt->fetchAll();
Double check your version of the query, because the one @Pepster64 gave you should do exactly that. A quick guess was you included the value field in the sub-query, which you don’t want to have.