Summary of three ways to implement ranking in MySQL without using order by

Summary of three ways to implement ranking in MySQL without using order by

Assuming business:

View the salary information of the second-ranked employee

Create a database

drop database if exists emps;
create database emps;
use emps;

create table employees(
    empId int primary key, -- employee number gender char(1) NOT NULL, -- employee gender hire_date date NOT NULL -- employee joining date );
create table salaries(
    empId int primary key, 
    salary double -- employee salary);
    
INSERT INTO employees VALUES(10001,'M','1986-06-26');
INSERT INTO employees VALUES(10002,'F','1985-11-21');
INSERT INTO employees VALUES(10003,'M','1986-08-28');
INSERT INTO employees VALUES(10004,'M','1986-12-01');
INSERT INTO salaries VALUES(10001,88958);
INSERT INTO salaries VALUES(10002,72527);
INSERT INTO salaries VALUES(10003,43311);
INSERT INTO salaries VALUES(10004,74057);

Solution

1. (Basic solution)

First find the highest salary in the salaries table, and then use this as a condition to find the second highest salary

The query statement is as follows:

select
	E.empId,E.gender,E.hire_date,S.salary
from
	employees E join salaries S 
on 
	E.empId = S.empId
where	
	S.salary=
	(
    select max(salary)from salaries 
    where 
        salary
        (select max(salary) from salaries)
    );
-- ---------------Query Results------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+

2. (Self-join query)

First, perform a self-join query on salaries. When s1<=s2 is linked and grouped by s1.salary, the value of count, that is, the number of people with higher salary than him, can be filtered by having to select people with count=2 to get the second highest salary.

The query statement is as follows:

select
	E.empId,E.gender,E.hire_date,S.salary
from
	employees E join salaries S 
on 
	E.empId = S.empId
where S.salary=
	(
    select 
        s1.salary
    from 
        salaries s1 join salaries s2 
    on 
        s1.salary <= s2.salary
    group by 
        s1.salary              
  	having
  	 count(distinct s2.salary) = 2
    );
-- ---------------Query Results------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+

3. (Self-join query optimization version)

The principle is the same as 2, but the code is much simpler. The above two methods are to introduce the last method. In many cases, group by and order by have their limitations. It is still meaningful for us beginners to master this more practical idea.

select
	E.empId,E.gender,E.hire_date,S.salary
from
	employees E join salaries S 
on
    S.empId =E.empId
where
    (select count(1) from salaries where salary>=S.salary)=2;
-- ---------------Query Results------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+

This is just a brief summary. If there are any mistakes, please point them out.

Summarize

This concludes this article about three ways to implement ranking in MySQL without using order by. For more relevant content about MySQL ranking without order by, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to data duplication when using limit+order by in MySql paging
  • Solution to the problem that order by is not effective in MySQL subquery
  • Detailed explanation of the pitfalls of mixing MySQL order by and limit
  • How to use MySQL group by and order by together
  • How to use indexes to optimize MySQL ORDER BY statements
  • Mysql sorting and paging (order by & limit) and existing pitfalls
  • Query process and optimization method of (JOIN/ORDER BY) statement in MySQL
  • MySQL briefly understands how "order by" works
  • Detailed explanation of Mysql's method of optimizing order by statement
  • Details on using order by in MySQL

<<:  Detailed explanation of the difference between tags and elements in HTML

>>:  Several principles for website product design reference

Recommend

docker cp copy files and enter the container

Enter the running container # Enter the container...

MySQL UNION operator basic knowledge points

MySQL UNION Operator This tutorial introduces the...

Detailed explanation of the transition attribute of simple CSS animation

1. Understanding of transition attributes 1. The ...

Three common methods for HTML pages to automatically jump after 3 seconds

In practice, we often encounter a problem: how to...

Get / delete method to pass array parameters in Vue

When the front-end and back-end interact, sometim...

WeChat applet implements text scrolling

This article example shares the specific code for...

Summary of methods to check whether the port is open in Linux

Method 1: Use lsof command We can use the lsof co...

Upgrade MySQL 5.1 to 5.5.36 in CentOS

This article records the process of upgrading MyS...

React Hooks Detailed Explanation

Table of contents What are hooks? Class Component...

Detailed explanation of the use of MySQL mysqldump

1. Introduction to mysqldump mysqldump is a logic...

Specific use of MySQL window functions

Table of contents 1. What is a window function? 1...

VUE+Express+MongoDB front-end and back-end separation to realize a note wall

I plan to realize a series of sticky note walls. ...

Detailed explanation of Getter usage in vuex

Preface Vuex allows us to define "getters&qu...

A brief analysis of MySQL's WriteSet parallel replication

【Historical Background】 I have been working as a ...