请问下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
这个用sql不好查询,可以发布站点文章的时候,动态生成每个分类下前20条的缓存,查询的时候直接取