请问下sql如何写,多对多关系如何分组,每组取对应的条数,如每组20条?

文章表:article

id,title ...

站点表:web

id,name ...

分类表:cate

id,name ...

中间表:article_cate_web

id,article_id,web_id,cate_id

1、站点跟分类是一对多关系,一个站点有多个分类,站点跟文章是多对多关系,文章跟分类是多对多关系
2、目的,通过站点id获取所有分类和每个分类下各20条文章
3、目前做法,先查询出所有该站点的分类,遍历分类拼接sql

`select * from `cate` where `web_id` = 1 
(select `article`.*, `article_cate_web`.`web_id` as `pivot_web_id`, `article_cate_web`.`cate_id` as `pivot_cate_id`,
`article_cate_web`.`article_id` as `pivot_article_id` from `article`
inner join `article_cate_web` on `article`.`id` = `article_cate_web`.`article_id` where `article_cate_web`.`web_id` = 1 and
`status` = 1 and `article_cate_web`.`cate_id` = 1 order by `article`.`id` desc limit 20) union all (select `article`.*, `article_cate_web`.`web_id` as `pivot_web_id`, `article_cate_web`.`cate_id` as `pivot_cate_id`,
`article_cate_web`.`article_id` as `pivot_article_id` from `article`
inner join `article_cate_web` on `article`.`id` = `article_cate_web`.`article_id` where `article_cate_web`.`web_id` = 1 and
`status` = 1 and `article_cate_web`.`cate_id` = 7 order by `article`.`id` desc limit 20) ...

4、求其他sql语句,可以的话转成ORM

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

每个分类下各 20 条文章

这个用sql不好查询,可以发布站点文章的时候,动态生成每个分类下前20条的缓存,查询的时候直接取

3年前 评论
讨论数量: 2

每个分类下各 20 条文章

这个用sql不好查询,可以发布站点文章的时候,动态生成每个分类下前20条的缓存,查询的时候直接取

3年前 评论

@WadeYu 这也是一个方案,谢谢

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!