Home  >  Article  >  Database  >  A detailed introduction to ranking functions in mysql

A detailed introduction to ranking functions in mysql

黄舟
黄舟Original
2017-08-09 15:33:111839browse

Ranking a certain field in the MySQL data table


1. Original table data As shown below. done_seconds is the completion time, and the requirement is to rank each piece of data based on this field.

A detailed introduction to ranking functions in mysql


##2. Enter the following SQL statement:

SELECT A.*,@rank:=@rank+1 AS pm FROM (SELECT * FROM task_news_user_done_list ORDER BY done_seconds) A, (SELECT  @rank:=0) B

A detailed introduction to ranking functions in mysql

3. After executing this statement, the pm field is added to the query results. The value of this field is the result of sorting based on done_seconds. Note the issue of ascending and descending order.

A detailed introduction to ranking functions in mysql

#4. In addition to individual fields, average values ​​can also be sorted. If you want to sort the average value of done_seconds for the same user_email in the above table, you can use the following sql statement:

SELECT A.*,@rank:=@rank+1 AS pm 
FROM 
(SELECT user_email, AVG(done_seconds) AS done_seconds FROM task_news_user_done_list GROUP BY user_email ORDER BY done_seconds) A, (SELECT  @rank:=0) B

A detailed introduction to ranking functions in mysql

5. The result after sorting is as shown below. The ranking at this time is the average ranking of all done_seconds of the same user_email.

A detailed introduction to ranking functions in mysql


##6. Of course, you can also join as needed where and other restrictions. As shown below.

Please click like if you find it useful.

A detailed introduction to ranking functions in mysql


#

The above is the detailed content of A detailed introduction to ranking functions in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn