当前位置:网站首页>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)边栏推荐
- Troubleshooting and optimization of easynvr version 5.0 Video Square snapshot not displayed
- Apache Druid's engineering practice in shopee
- Spark broadcast variables and accumulators (cases attached)
- Wechat applet camera compressed image is Base64
- How to store, manage and view family photos in an orderly manner?
- Soft exam information system project manager_ Information system comprehensive testing and management - Senior Information System Project Manager of soft test 027
- Tencent cloud server CVM system tool configuration
- Pnas: amygdala individual specific functional connectivity: Fundamentals of precision psychiatry
- Hypervisor Necromancy; Recover kernel protector (1)
- Function recursion and iteration
猜你喜欢

Microservice Optimization: internal communication of microservices using grpc

8. greed

Xgboost Guide

6. template for integer and real number dichotomy

Understand GB, gbdt and xgboost step by step

Log a log4j2 vulnerability handling

C language series - Section 4 - arrays

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

Vulnhub DC-5

Spark broadcast variables and accumulators (cases attached)
随机推荐
Zoom/skype/ nailing / live broadcast / conference / online video real-time subtitle generation and translation, simultaneous interpretation
Reinforcement learning series (IV) -policygradient example
Learning notes of recommendation system (1) - Collaborative Filtering - Theory
An article shows you the difference between high fidelity and low fidelity prototypes
There is no WM data in the primary commodity master data store view of SAP retail
Optimization method of live weak network
OVS port traffic statistics practice
Detailed explanation of online reputation management
Understand GB, gbdt and xgboost step by step
Qingdao stadium has made headlines again, but it has nothing to do with sports
Schedule tasks to periodically restart remote services or restart machines
Record a penetration caused by log4j
Win11 client remote ECS black screen
3. install and deploy Mgr cluster | explain Mgr in simple terms
6. template for integer and real number dichotomy
How to prohibit copying and copying files to the local server remote desktop
Use Sakura FRP intranet penetration service to build your own website / game server
Quic implementation in rust --- Quinn
Goframe framework (RK boot): rapid configuration of server CORS
Tencent cloud server CVM system tool configuration