I have the following table
Table structure:
CREATE TABLE IF NOT EXISTS `people` (
`name` varchar(10) NOT NULL,
`age` smallint(5) u
Question 1 : What I made mistake here and why this MAX function is not return the relevant row information?
You need to read up on the group by
clause.
MySQL is being a lot more permissive than it should, introducing confusion in the process. Basically, any column without an aggregate should be included in the group by
clause. But MySQL syntactic sugar allows to "forget" columns. When you do, MySQL spits out an arbitrary value from the set that it's grouping by. In your case, the first row in the set is bob
, so it returns that.
Question 2: Which one is good to use, to increase performance MAX function or ORDER BY clause?
Your first statement (using max()
without a group by
) is simply incorrect.
If you want one of the oldest users, order by age desc limit 1
is the correct way to proceed.
If you want all of the oldest users, you need a subselect:
SELECT p.* FROM people p WHERE p.age = (select max(subp.age) from people subp);