I've a table like below on my MySQL database:
employee
-------------------------
id name num
1 Jack 1
2 John 1
3 Jack 2
4 Steve 1
5 Jack 3
6 Steve 2
7 Carol 1
The thing I want to do is to retrieve names with the highest "num" value.
For example:
5 Jack 3
There more than one records named Jack but I want to get the one with the maximum "num" value.
I've tried to use the query below:
SELECT MAX(num),id,name FROM `employee`
But it returns the id and name of first record (first "Jack") but the num of the latest.
MAX(num) id num
-----------------------
3 1 Jack
Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.
SELECT num,id,name FROM `employee` order by num desc
This query will also return all the records including the smaller ones.
id name num
-------------------------
3 5 Jack
2 3 Jack
2 6 Steve
1 1 Jack
1 2 John
1 4 Steve
1 7 Carol
When I try to group by name, it returns the records grouped by name but again only the small records.
The both of the queries below give the same result:
SELECT num,id,name FROM `employee` group by name order by num desc
SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc
Again, it groups with only the first and smallest records.
id name num
1 Jack 1
2 John 1
4 Steve 1
7 Carol 1