当前位置:网站首页>MySQL gets the top 1 and top n records after grouping
MySQL gets the top 1 and top n records after grouping
2022-06-23 02:56:00 【It workers】
Sometimes there are some needs , After query grouping The maximum of , The whole row of records or grouped records where the minimum value is located top n The record of the line , In some other databases, there may be window functions that can be found in various aspects , however MySQL Without these functions , There is no direct way to find out , You can query through the following methods .
preparation
The structure of the test table is as follows :
root:test> show create table test1\G
*************************** 1. row ***************************
Table: test1
Create Table: CREATE TABLE `test1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`course` varchar(20) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)insert data :
insert into test1(name,course,score)
values
(' Zhang San ',' Chinese language and literature ',80),
(' Li Si ',' Chinese language and literature ',90),
(' Wang Wu ',' Chinese language and literature ',93),
(' Zhang San ',' mathematics ',77),
(' Li Si ',' mathematics ',68),
(' Wang Wu ',' mathematics ',99),
(' Zhang San ',' English ',90),
(' Li Si ',' English ',50),
(' Wang Wu ',' English ',89);View results :
root:test> select * from test1; +----+--------+--------+-------+ | id | name | course | score | +----+--------+--------+-------+ | 1 | Zhang San | Chinese language and literature | 80 | | 2 | Li Si | Chinese language and literature | 90 | | 3 | Wang Wu | Chinese language and literature | 93 | | 4 | Zhang San | mathematics | 77 | | 5 | Li Si | mathematics | 68 | | 6 | Wang Wu | mathematics | 99 | | 7 | Zhang San | English | 90 | | 8 | Li Si | English | 50 | | 9 | Wang Wu | English | 89 | +----+--------+--------+-------+
TOP 1
Check each course The highest score Students and grades
1、 Use self connect 【 recommend 】
root:test> select a.name,a.course,a.score from
-> test1 a
-> join (select course,max(score) score from test1 group by course) b
-> on a.course=b.course and a.score=b.score;
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | Chinese language and literature | 93 |
| Wang Wu | mathematics | 99 |
| Zhang San | English | 90 |
+--------+--------+-------+
3 rows in set (0.00 sec)2、 Use related subqueries
root:test> select name,course,score from test1 a
-> where score=(select max(score) from test1 where a.course=test1.course);
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | Chinese language and literature | 93 |
| Wang Wu | mathematics | 99 |
| Zhang San | English | 90 |
+--------+--------+-------+
3 rows in set (0.00 sec)perhaps
root:test> select name,course,score from test1 a
-> where not exists(select 1 from test1 where a.course=test1.course and a.score < test1.score);
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | Chinese language and literature | 93 |
| Wang Wu | mathematics | 99 |
| Zhang San | English | 90 |
+--------+--------+-------+
3 rows in set (0.00 sec)TOP N
N>=1
Check the top two students of each course and their grades
1、 Use union all
If the result set is small , You can use the program to query a single grouping result and then piece it up , You can also use union all
root:test> (select name,course,score from test1 where course=' Chinese language and literature ' order by score desc limit 2)
-> union all
-> (select name,course,score from test1 where course=' mathematics ' order by score desc limit 2)
-> union all
-> (select name,course,score from test1 where course=' English ' order by score desc limit 2);
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | Chinese language and literature | 93 |
| Li Si | Chinese language and literature | 90 |
| Wang Wu | mathematics | 99 |
| Zhang San | mathematics | 77 |
| Zhang San | English | 90 |
| Wang Wu | English | 89 |
+--------+--------+-------+
6 rows in set (0.01 sec)2、 Self left connection
root:test> select a.name,a.course,a.score
-> from test1 a left join test1 b on a.course=b.course and a.score<b.score
-> group by a.name,a.course,a.score
-> having count(b.id)<2
-> order by a.course,a.score desc;
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | mathematics | 99 |
| Zhang San | mathematics | 77 |
| Zhang San | English | 90 |
| Wang Wu | English | 89 |
| Wang Wu | Chinese language and literature | 93 |
| Li Si | Chinese language and literature | 90 |
+--------+--------+-------+
6 rows in set (0.00 sec)3、 Correlation subquery
root:test> select *
-> from test1 a
-> where 2>(select count(*) from test1 where course=a.course and score>a.score)
-> order by a.course,a.score desc;
+----+--------+--------+-------+
| id | name | course | score |
+----+--------+--------+-------+
| 6 | Wang Wu | mathematics | 99 |
| 4 | Zhang San | mathematics | 77 |
| 7 | Zhang San | English | 90 |
| 9 | Wang Wu | English | 89 |
| 3 | Wang Wu | Chinese language and literature | 93 |
| 2 | Li Si | Chinese language and literature | 90 |
+----+--------+--------+-------+
6 rows in set (0.01 sec)4、 Use user variables
root:test> set @num := 0, @course := '';
Query OK, 0 rows affected (0.00 sec)
root:test>
root:test> select name, course, score
-> from (
-> select name, course, score,
-> @num := if(@course = course, @num + 1, 1) as row_number,
-> @course := course as dummy
-> from test1
-> order by course, score desc
-> ) as x where x.row_number <= 2;
+--------+--------+-------+
| name | course | score |
+--------+--------+-------+
| Wang Wu | mathematics | 99 |
| Zhang San | mathematics | 77 |
| Zhang San | English | 90 |
| Wang Wu | English | 89 |
| Wang Wu | Chinese language and literature | 93 |
| Li Si | Chinese language and literature | 90 |
+--------+--------+-------+
6 rows in set (0.00 sec)边栏推荐
- Apache Druid's engineering practice in shopee
- What is ISBN code and how to make it
- Essentials of fleet video playback and fleet videoplayer video playback components
- 2022-01-27: heater. Winter has come. Your task is to design a
- Schedule tasks to periodically restart remote services or restart machines
- Xgboost Guide
- Troubleshooting and solution of 4K video cannot be played on easydss live video on demand platform
- Chaoscraft: join your girlfriend in Hackathon show -- Interview with the skate team
- The performance of the new Tokio scheduler is improved by 10 times
- How to use pictures in Excel in PPT template
猜你喜欢

Log a log4j2 vulnerability handling

Soft exam information system project manager_ Contract Law_ Copyright_ Implementation Regulations - Senior Information System Project Manager of soft exam 030

Xgboost Guide

8. greed

Soft exam information system project manager_ Information system comprehensive testing and management - Senior Information System Project Manager of soft test 027

Vulnhub DC-5

C language series - Section 4 - arrays

6. template for integer and real number dichotomy
What is sitelock? What is the function?

Xgboost principle
随机推荐
Xiamen's hidden gaopuge smart park has finally been uncovered
Source code analysis | activity setcontentview I don't flash
Reading redis source code (II) underlying data structure
Reinforcement learning series (IV) -policygradient example
Learning about urldns chains
Detailed explanation of online reputation management
2022-01-27: heater. Winter has come. Your task is to design a
Vulnhub DC-5
EDI project cases of customers in medical device industry
PHP Base64 image processing Encyclopedia
Docker builds MySQL master-slave
About the use of mock framework
2D visual empowerment smart water green intensive development
The performance of the new Tokio scheduler is improved by 10 times
February 2, 2022: the closest binary search tree value II. Given a non empty two
Troubleshooting and solution of 4K video cannot be played on easydss live video on demand platform
Reading redis source code (VI) multi threading of redis 6.0
An article shows you the difference between high fidelity and low fidelity prototypes
Aikuai multi dialing + load balancing overlay bandwidth
Function recursion and iteration