列表查询+n 条附属结果,请教怎么查询比较优化

2021-09-22 14:53:17 +08:00
 zjttfs

例如

article文章表

字段 注释
id 文章主键
title 文章标题

comment评论表

字段 注释
id 评论主键
article_id 文章主键
content 评论内容

现查询文章列表 , 要求查询 10 篇文章,每篇文章附上最新的 3 条评论.

我现在的做法是查询出 10 篇文章.然后在代码里循环查询每篇文章的最新 3 条评论.

总计 1+10 次查询....

请教有什么更好的办法,减少查询次数吗?

子查询?或者再 mysql 中做函数 /存储过程?

1624 次点击
所在节点    MySQL
16 条回复
dqzcwxb
2021-09-22 14:56:52 +08:00
循环查询改为 in 查询后在代码中 join
westoy
2021-09-22 15:00:30 +08:00
不要搞复杂

你现在这种其实 SQL Cache 命中率更高, 也更容易在后期做 k-v cache.........
Bigglesworth
2021-09-22 15:00:49 +08:00
减少次数,就 join 起来查?
zjttfs
2021-09-22 15:06:49 +08:00
@dqzcwxb
@Bigglesworth

请教下怎么 join?
文章的评论可能很多大于 3 条.
没有 limit 限制,不是会查询很多出来吗?
zjttfs
2021-09-22 15:07:07 +08:00
@westoy

尴尬.没看懂...
zilongzixue
2021-09-22 15:17:51 +08:00
mybatis 一对多查询
lin07hui
2021-09-22 15:23:04 +08:00
orm 吧
hingbong
2021-09-22 15:33:28 +08:00
```
val sqlStep = articles.map { article ->
select * from comment where article_id = article1.id limit 3
}.reduce { left, right ->
left.union(right)
}

sqlStep.fetch()
```
我日常用 kotlin + jooq,这个需求大概就是这个思路查询
hingbong
2021-09-22 15:34:15 +08:00
```
val sqlStep = articles.map { article ->
select * from comment where article_id = article.id limit 3
}.reduce { left, right ->
left.union(right)
}

sqlStep.fetch()
```
手误
tangtj
2021-09-22 15:35:56 +08:00
我觉得你的逻辑是 ok 的。1 + n 查询没啥问题,评论的查询也很方便上缓存。
dqzcwxb
2021-09-22 15:50:25 +08:00
@zjttfs #4 那可能没法用 in 查询,只能串行改并行提升效率了.建议使用 Completablefuture 这样也方便做 cache
wolfie
2021-09-22 15:52:04 +08:00
select from comment where id = 1 order by id desc limit 3
union all
select from comment where id = 2 order by id desc limit 3

语法可能错误,用子查询包一下
zjttfs
2021-09-22 15:53:10 +08:00
@westoy

刚才忙没太细看,再看了一次. 懂您的意思了.

@tangtj

好的. 感谢.
zjttfs
2021-09-22 15:55:00 +08:00
@zilongzixue

我查下资料.谢谢
zjttfs
2021-09-22 15:57:28 +08:00
@wolfie

感谢
zzfer
2021-09-22 16:00:43 +08:00
mybatis 一对多标签 collection 可以限制查三条。但这样其实效果和你循环查询一样,只不过在一次连接查完。限制十条数据还行,查的多了速度一样很慢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/803388

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX