mysql - 获取每组分组结果的前5条记录

时间:2016-03-04 07:05:23

标签: mysql

select *,COUNT(feed_id) from
 (SELECT feed_contents.*, feed.feed_url, feed.lang_direction, feed.feed_title 
    FROM feed_contents 
    INNER JOIN feed ON feed_contents.feed_id = feed.feed_id 
    INNER JOIN user_feeds ON feed_contents.feed_id = user_feeds.feed_id 
    WHERE user_feeds.user_id = 13 
    AND DATE(feed_contents.content_date) >= CURDATE() - INTERVAL 90 DAY 
    ORDER BY feed_contents.content_date desc) as tbl 
group by feed_id
order by content_date desc 
limit 0,20

我有这个查询来从多个表中获取结果, 结果它返回一个针对feed_id的记录, 我希望每个feed_is有5条记录

输出就像 http://screencast.com/t/HHxNOOSdSX4S

我希望每个

最多5个

1 个答案:

答案 0 :(得分:1)

您可以使用变量:

orderid

变量"SELECT * FROM Orders ORDER BY orderid DESC LIMIT 20"; 用于枚举每个SELECT feed_id, content_date, feed_url, lang_direction, feed_title FROM ( SELECT feed_id, content_date, feed_url, lang_direction, feed_title, @rn := IF(@fid = feed_id, @rn + 1, IF(@fid := feed_id, 1, 1)) AS rn FROM ( SELECT feed_contents.feed_id, feed_contents.content_date, feed.feed_url, feed.lang_direction, feed.feed_title FROM feed_contents INNER JOIN feed ON feed_contents.feed_id = feed.feed_id INNER JOIN user_feeds ON feed_contents.feed_id = user_feeds.feed_id WHERE user_feeds.user_id = 13 AND DATE(feed_contents.content_date) >= CURDATE() - INTERVAL 90 DAY) AS tbl CROSS JOIN (SELECT @rn := 0, @fid := 0) AS vars ORDER BY feed_id, content_date DESC) AS s WHERE s.rn <= 5 分区中的记录。 @rn值更改后,feed_id将重置为1,以便开始计算下一个分区。记录按字段feed_id按降序编号。