使用SQL获取表的前k个记录/行

时间:2015-05-07 16:19:57

标签: mysql sql

根据下面的表格,如何在不使用kLIMIT 的情况下获取的第一行TOP行?

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

k=3的所需结果:

+--------+-------+-----+
| Bob    | 1     | 32  |
| Jill   | 1     | 34  |
| Shawn  | 1     | 42  |
+--------+-------+-----+

k=4的所需结果:

+--------+-------+-----+
| Bob    | 1     | 32  |
| Jill   | 1     | 34  |
| Shawn  | 1     | 42  |
| Jake   | 2     | 29  |
+--------+-------+-----+

我需要复制MySQL的LIMIT函数而不使用它。

3 个答案:

答案 0 :(得分:4)

您可以通过对派生表中的行进行编号,然后选择行数达到阈值的行来执行此操作。

对于MySQL,查询可能如下所示:

SELECT 
    *
FROM
    (SELECT 
        @row_number:=@row_number + 1 AS row_number,
            person,
            `group`,
            age
    FROM
        your_table, (SELECT @row_number:=0) AS r
    ORDER BY `group` , age) x
WHERE
    row_number <= 3;

Sample SQL Fiddle

答案 1 :(得分:3)

行。如果不允许变量,你仍然可以这样做......

SELECT some, stuff 
  FROM an_instance x 
  JOIN another_instance y 
    ON (y.something < x.something) 
    OR (y.something = x.something AND y.some_other_thing <= x.some_other_thing) 
 GROUP  
    BY x.something,x.some_other_thing
HAVING COUNT(*) <= whatever;

......但它会在较大的数据集上出色地缩放。

答案 2 :(得分:2)

您似乎首先按组号排序,然后按年龄排序。你可以做的是按顺序选择行,并使用变量将它们的位置存储在列表中。

完成后,您可以选择位置小于或等于参数k的行,如下所示:

SET @position := 0;

SELECT person, groupCol, age
FROM(
  SELECT person, groupCol, age, @position := @position + 1 AS position
  FROM myTable
  ORDER BY groupCol, age) tmp
WHERE tmp.position <= 3;