2016-05-15 62 views
1

這裏是我的表:如何爲每個類別選擇準確數量的文章?

CREATE TABLE IF NOT EXISTS `category` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `title` varchar(50) NOT NULL, 
    `post_limit` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; 

INSERT INTO `category` (`id`, `title`, `post_limit`) VALUES 
(1, 'News', 2), 
(2, 'Sport', 2), 
(3, 'Science', 1), 
(4, 'Games', 1); 

CREATE TABLE IF NOT EXISTS `article` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `title` varchar(50) NOT NULL, 
    `category_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `category_id` (`category_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ; 

INSERT INTO `article` (`id`, `title`, `category_id`) VALUES 
(1, 'news article 1', 1), 
(2, 'news article 2', 1), 
(3, 'news article 3', 1), 
(4, 'sports article 1', 2), 
(5, 'sports article 2', 2), 
(6, 'sports article 3', 2), 
(7, 'Science article 1', 3), 
(8, 'Science article 2', 3), 
(9, 'games article 1', 4), 
(10, 'games article 2', 4); 

我需要做的是選擇10篇(ORDER BY article.id DESC),但記住,每一個類別都有post_limit,因此,例如,我們不能把category_id=1 5帖子如果post_limit=2軸承。

預先感謝您。

更新1: 結果應該是:

10 games article 2  4 
8 science article 2 3 
6 sports article 3 2 
5 sports article 2 2 
3 news article 3  1 
+0

你能提供樣品數據和理想的結果嗎? –

+0

我們可以看到你試過的嗎? – halfer

+0

我會盡快上線,我現在在手機上 – CroiOS

回答

1

我想你需要枚舉應用post_limit的文章。你可以用一個子查詢做到這一點:

select a.* 
from (select a.*, 
      (@rn := if(@c = a.category_id, @rn + 1, 
         if(@c := a.category_id, 1, 1) 
         ) 
      ) as rn 
     from articles a cross join 
      (select @rn := 0, @c := -1) params 
     order by category_id 
    ) a join 
    category c 
    on c.id = a.category_id 
where a.rn <= c.post_limit 
limit 10; 

在實踐中,你可能想在limit之前order by有過哪些文章更多的控制。同樣,您可能需要子查詢中order by上的另一個鍵來控制文章。 。 。如order by category_id, id desc以獲取最新的文章。

+0

使用您的解決方案+添加兩個更改,以獲得我想要的確切結果:https://dl.dropboxusercontent。 com/u/77033905/ss/2016-05-15_2146.png – CroiOS

+0

您的解決方案是可以的,但如果其中一個類別具有post_limit = 0或post_limit = NULL,則缺少一個類別,則應打印所有帖子 – CroiOS

2

要限制每個類別的計數的類別的post_limit

select c.id, c.title, least(post_limit, count(a.id)) 
from category c 
left join article a on category_id = c.id 
group by 1, 2 -- or "group by c.id, c.title" if you prefer the verbose style 

SQLFiddle

1
select max(a.id) "Id", 
     max(a.title) "Title", 
     a.category_id "Category_Id, 
     max(c.id), 
     max(c.title), 
     count(*), 
     max(c.post_limit) 
from article a 
left outer join article b on b.category_id = a.category_id AND b.id>=a.id 
left outer join category c on a.category_id = c.id 
group by a.id 
having count(a.id) <= max(c.post_limit) 
order by max(a.id) desc 
limit 10 

這將每篇文章(表a)和檢索在同一類別中的所有物品具有較高的ID值(表b)。

然後,您通過文章ID(a.id)分組,並且只選擇數量低於類別post_limit的組。

相關問題