2016-03-04 53 views
0
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一個記錄, 結果我想要5個記錄對每個feed_isMySQL的 - 取得前5名的記錄爲每個組分組結果

輸出類似 http://screencast.com/t/HHxNOOSdSX4S

我想最多5從每個

回答

1

可以使用變量此:

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分區內的記錄。一旦feed_id值發生變化,@rn正被重置爲1,以開始計算下一個分區。記錄根據字段content_date以降序編號。

+0

ooo非常感謝你Giorgos先生, 它對我來說永遠不會那麼容易,你讓它變得如此簡單,非常感謝你的幫助 –

相關問題