我有两个名为类别和内容的表(每个类别可以有很多内容),这是我的查询
SELECT * FROM categories ca
LEFT JOIN content co ON co.cat_id=ca.id
我想对其进行查询以获取每个类别的10个内容的限制。
我应该如何查询?
rank
MySQL上没有功能。
您应该使用变量。我为你写了这个摘录。将其转换为您自己的模式:
MySQL 5.6模式设置:
--c are categories
create table c ( id int, n varchar(100) );
--p are contents
create table p ( id int, fk_c int, n varchar(100) );
insert into c values
(1, 'A'),
(2, 'B');
insert into p values
(1,1,'a'),
(2,1,'b'),
(3,1,'d'), <-- id=3, over the limit set to 2
(4,2,'e');
查询:
select * from (
SELECT p.*,
@n := ( case when @c <> c.id then 1 else @n+1 end) as "num",
@c := c.id as "prev c"
FROM c left outer join p on c.id = p.fk_c,
(SELECT @n := 0, @c = 0) r
) p
where p.num <= 2 <-- limiting to 2.
结果:
| id | fk_c | n | num | prev c |
|----|------|---|-----|--------|
| 1 | 1 | a | 1 | 1 |
| 2 | 1 | b | 2 | 1 |
<-- id=3 missing ;)
| 4 | 2 | e | 1 | 2 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句