SQL-GROUP BY子句

时间:2018-10-17 16:06:49

标签: mysql sql group-by

我有一个表,其中每个记录type中需要最新的2行。使用GROUP BY。 例如,从下面的图片中,我想要得到的最后2条记录取决于每种date类型的page列。我知道会使用GROUP BY,但我对此不太熟悉。。谢谢

enter image description here

4 个答案:

答案 0 :(得分:1)

长话短说,一旦您拥有很少的不同类型,就可以使用UNION方式:

SELECT * FROM (SELECT * FROM table WHERE page = 'sometype' ORDER BY date limit 2) t
UNION ALL 
SELECT * FROM (SELECT * FROM table WHERE page = 'someothertype' ORDER BY date limit 2) t
UNION ALL 
SELECT * FROM (SELECT * FROM table WHERE page = 'otherothertype' ORDER BY date limit 2) t
...

只需对您拥有的每种“页面”类型重复此操作。

如果此解决方案不适合您,请看一下这篇文章:http://www.sqlines.com/mysql/how-to/get_top_n_each_group

欢呼声

Nikao

答案 1 :(得分:0)

您可以将关联子查询与limit子句一起使用:

select t.*
from table t
where id in (select t1.id
             from table t1
             where t1.page = t.page
             order by t1.date desc
             limit 2
            );

但是,仅GROUP BY不能满足您的需要,您可能需要JOIN

答案 2 :(得分:0)

如果您的mysql版本是8+,则可以使用row_number窗口函数,但是如果低于8,则可以使用以下生成行号的方法

set @num := 0, @page:= '';

select x.*
from (
   select t.*,
      @num := if(@page= page, @num + 1, 1) as row_number,
      @page:= page as d
  from table t
  order by date desc
) as x where x.row_number <= 2;

答案 3 :(得分:0)

您不能仅使用GROUP BY来获得所需的结果。 您只能使用子查询和GROUP_CONCAT。看到这个: Using LIMIT within GROUP BY to get N results per group?

如果您的MySQL版本不支持这些功能,则需要使用其他方法:

  1. 获取所有不同页面类型的列表:SELECT DISTINCT page;
  2. 以编程方式遍历页面类型列表和主表中的SELECT ... LIMIT 2;

您应该意识到,如果您的数据库很大,这两种方法的性能可能会大不相同。

相关问题