這裏是我的表:如何爲每個類別選擇準確數量的文章?
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
你能提供樣品數據和理想的結果嗎? –
我們可以看到你試過的嗎? – halfer
我會盡快上線,我現在在手機上 – CroiOS