Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Select top n max values?

Tags:

mysql

max

I am really confused about the query that needing to return top N rows having biggest values on particular column.

For example, if the rows N-1, N, N + 1 have same values. Must I return just top N or top N + 1 rows.

like image 677
Hoa Vu Avatar asked Nov 07 '13 03:11

Hoa Vu


People also ask

How do I find Top 10 in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.

How do I select the highest number in MySQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How do you get a record with maximum value for each group?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).


1 Answers

If you do:

select * from t order by value desc limit N 

You will get the top N rows.

If you do:

select * from t join      (select min(value) as cutoff       from (select value             from t             order by value             limit N            ) tlim     ) tlim     on t.value >= tlim; 

Or you could phrase this a bit more simply as:

select * from t join      (select value       from t       order by value       limit N     ) tlim     on t.value = tlim.value; 

The following is conceptually what you want to do, but it might not work in MySQL:

select * from t where t.value >= ANY (select value from t order by value limit N) 
like image 186
Gordon Linoff Avatar answered Sep 21 '22 09:09

Gordon Linoff