以下是我的表格:
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个帖子,我们就不能1}}。
提前谢谢。
更新1: 结果应该是:
post_limit=2
答案 0 :(得分: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 :(得分: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;
在实践中,您可能希望在order by
之前limit
能够更好地控制哪些文章。同样,您可能希望子查询中order by
上的另一个键来控制文章。 。 。例如order by category_id, id desc
以获取最新文章。
答案 2 :(得分: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类别的组。