每组获得N个MYSQL

时间:2012-06-22 15:06:17

标签: php mysql mysqli

这不是同样的问题:Using LIMIT within GROUP BY to get N results per group?

但我承认它很相似。

我需要选择每人前两行。 行按照收到的年份排序

问题:有可能在同一个月输入2个数据(日期输入YYYY-MM)

我附带的查询(在提到的问题之后)被困在一个BIG循环中。

SELECT *
FROM `table_data` as b
WHERE (
    SELECT count(*) FROM `table_data` as a
        WHERE a.Nom = b.Nom and a.year < b.year
    ) <= 2;

示例数据:

  A  |   year   |  Nom
---------------------
  b  |  2011-01 | Tim
---------------------
  d  |  2011-01 | Tim
---------------------
  s  |  2011-01 | Tim
---------------------
  a  |  2011-03 | Luc
---------------------
  g  |  2011-01 | Luc
---------------------
  s  |  2011-01 | Luc

应该导出:

  A  |   year   |  Nom
---------------------
  b  |  2011-01 | Tim
---------------------
  d  |  2011-01 | Tim
---------------------
  a  |  2011-03 | Luc
---------------------
  g  |  2011-01 | Luc

1 个答案:

答案 0 :(得分:1)

(
 -- First get a set of results as if you only wanted the latest entry for each
 -- name - a simple GROUP BY from a derived table with an ORDER BY
  SELECT *
  FROM (
    SELECT *
    FROM `table_data`
    ORDER BY `year` DESC
  ) `a`
  GROUP BY `Nom`
)
UNION
(
 -- Next union it with the set of result you get if you apply the same criteria
 -- and additionally specify that you do not want any of the rows found by the
 -- first operation
  SELECT *
  FROM (
    SELECT *
    FROM `table_data`
    WHERE `id` NOT IN (
      SELECT `id`
      FROM (
        SELECT *
        FROM `table_data`
        ORDER BY `year` DESC
      ) `a`
      GROUP BY `Nom`
    )
    ORDER BY `year` DESC
  ) `b`
  GROUP BY `Nom`
)
 -- Optionally apply ordering to the final results
ORDER BY `Nom` DESC, `year` DESC

我确信有一个较短的方法,但现在我不能为我的生活弄清楚它是什么。但是does work - 假设你有一个主键(你应该)并且它被称为id