Home > Database > Mysql Tutorial > body text

A detailed introduction to ranking functions in mysql

黄舟
Release: 2017-08-09 15:33:11
Original
1895 people have browsed it

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template