在不扫描完整表的情况下在MySQL中获取每个组中的最后5行

时间:2019-07-09 13:19:40

标签: mysql

我想从每个组中获取最后2行而不扫描整个表。我已经尝试并得到了结果,但是查询可以进行全表扫描

我有一张下面的桌子

+--------+-------+-----+
| Person | Group | Age |
+--------+-------+-----+
| Bob    | 1     | 32  |
| Jill   | 1     | 34  |
| Shawn  | 1     | 42  |
| Jake   | 2     | 29  |
| Paul   | 2     | 36  |
| Laura  | 2     | 39  |
+--------+-------+-----+

我得到的结果就像

+--------+-------+-----+
| Person | Group | Age |
+--------+-------+-----+
| Shawn  | 1     | 42  |
| Jill   | 1     | 34  |
| Laura  | 2     | 39  |
| Paul   | 2     | 36  |
+--------+-------+-----+

检查以下查询,它正在全表扫描中工作。请提出避免全表扫描的建议

SELECT a.person, a.group, a.age FROM person AS a WHERE 
(SELECT COUNT(*) FROM person AS b 
WHERE b.group = a.group AND b.age >= a.age) <= 2 
ORDER BY a.group ASC, a.age DESC

1 个答案:

答案 0 :(得分:0)


  CREATE TABLE people(
   person  varchar(200),
  groupid int,
  age  int 
  );
INSERT INTO people(person,groupid,age) values("Bob",1,32);
INSERT INTO people(person,groupid,age) values("Jill ",1,34);
INSERT INTO people(person,groupid,age) values("Shawn",1,42);
INSERT INTO people(person,groupid,age) values("Jake",2,29);
INSERT INTO people(person,groupid,age) values("Paul",2,36);
INSERT INTO people(person,groupid,age) values("Laura",2,39);
INSERT INTO people(person,groupid,age) values("Jake",3,39);

 -- some how able to count two rows.  If less than two rows, throw 1
 SELECT groupid, 
 CASE  WHEN  count(groupid)>=2  THEN 2
       WHEN  count(groupid) = 1 THEN 1 
       ELSE 0 END 
 as possiblerows
 from people 
 group by groupid;


+---------+--------------+
| groupid | possiblerows |
+---------+--------------+
|       1 |            2 |
|       2 |            2 |
|       3 |            1 |
+---------+--------------+

我知道这不是完整的解决方案。但这可能会让您入门,可以在提取行之前对其进行计数。