如何在 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)
廣告