如何在mysql中为每个组获得前300行?

时间:2017-03-13 03:00:16

标签: mysql

我有这样的表

dlrecipientid  dlrecipientlistid
1                  1
2                  1
..                 ..
999                1
1000               1
1001               2
1002               2
..                 ..
1999               2
2000               2

如何查询并获得前300行dlrecipientlistid

eample

dlrecipientid  dlrecipientlistid
1                  1
2                  1
..                 ..
299                1
300                1
1001               2
1002               2
..                 ..
1299               2
1300               2

我需要在mysql中查询

4 个答案:

答案 0 :(得分:1)

您可以通过以下方式进行自我加入:

  SELECT tbl1.* FROM your_table AS tbl1
  LEFT OUTER JOIN your_table AS tbl2 
    ON (tbl1.dlrecipientlistid= tbl2.dlrecipientlistid 
        AND tbl1.dlrecipientid > tbl2.dlrecipientid)
  GROUP BY tbl1.dlrecipientid  
  HAVING COUNT(*) < 300
  ORDER BY tbl1.dlrecipientid,tbl1.dlrecipientlistid DESC;

我已在SQLFIDDLE

中更新了查询并经过了充分测试

答案 1 :(得分:0)

(
 select *
 from mytable 
 where `group` = 1
  LIMIT 300
 )
UNION ALL
(
select *
from mytable 
where `group` = 2
LIMIT 300

答案 2 :(得分:0)

似乎需要使用变量:

select
    dlrecipientlistid,
    dlrecipientid,
    @rowno := case when @grp = dlrecipientlistid then @rowno + 1 else 1 end as rowno,
    @grp := dlrecipientlistid
from yourtable
cross join (select @rowno := 0, @grp := null) t
order by dlrecipientlistid, dlrecipientid
having rowno <= 300

答案 3 :(得分:0)

你可以试试这个。

select * from <table_name> limit 300;