What is the best way to select the first two records of each group by a “SELECT” command?

后端 未结 3 710
别跟我提以往
别跟我提以往 2021-02-10 05:30

For instance I have the following table:

id group data
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
5 2 aaa
6 3 aaa
7 3 aaa
8 3 aaa

What is the best way to

3条回答
  •  温柔的废话
    2021-02-10 05:51

    I like this trick, that makes use of GROUP_CONCAT aggregate function, and FIND_IN_SET:

    SELECT
      Tablename.*
    FROM
      Tablename INNER JOIN (
        SELECT `group`, GROUP_CONCAT(id ORDER BY id) ids
        FROM Tablename
        GROUP BY `group`) grp ON
      Tablename.`group` = grp.`group` AND
      FIND_IN_SET(Tablename.id, ids)<=2
    ORDER BY
      Tablename.`group`, Tablename.id
    

    Performances can't be too good, as it can't make use of an index.

    Or you can also use this:

    SELECT t1.id, t1.`group`, t1.data
    from
      Tablename t1 INNER JOIN Tablename t2
      ON t1.`group` = t2.`group` AND t1.id>=t2.id
    GROUP BY
      t1.id, t1.`group`, t1.data
    HAVING
      COUNT(*)<=2
    ORDER BY
      t1.`group`, t1.id, t1.data
    

提交回复
热议问题