如何在 MySQL 中选择每组的前 2 行?
若要选择每组的前 2 行,请与子查询一起使用 where 条件。我们创建一个表。创建表的查询如下
mysql> create table selectTop2FromEachGroup -> ( -> Name varchar(20), -> TotalScores int -> ); Query OK, 0 rows affected (0.80 sec)
现在,使用插入命令在表中插入一些记录。查询如下
mysql> insert into selectTop2FromEachGroup values('John',32); Query OK, 1 row affected (0.38 sec) mysql> insert into selectTop2FromEachGroup values('John',33); Query OK, 1 row affected (0.21 sec) mysql> insert into selectTop2FromEachGroup values('John',34); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',35); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',36); Query OK, 1 row affected (0.14 sec) mysql> insert into selectTop2FromEachGroup values('Carol',37); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录。查询如下
mysql> select *from selectTop2FromEachGroup;
输出如下
+-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 32 | | John | 33 | | John | 34 | | Carol | 35 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 6 rows in set (0.00 sec)
以下是使用 where 条件和子查询选择每组的前 2 行的查询
mysql> select *from selectTop2FromEachGroup tbl -> where -> ( -> SELECT COUNT(*) -> FROM selectTop2FromEachGroup tbl1 -> WHERE tbl1.Name = tbl.Name AND -> tbl1.TotalScores >= tbl.TotalScores -> ) <= 2 ;
输出如下
+-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 33 | | John | 34 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 4 rows in set (0.06 sec)
广告