gpt4 book ai didi

mysql - Rails 选择每组前 n 条记录(内存泄漏)

转载 作者:行者123 更新时间:2023-11-28 23:10:38 25 4
gpt4 key购买 nike

我有使用 find_by_sql 的方法,它返回每个来源的 10 条最新记录

def latest_results
Entry.find_by_sql(["
select x.id,x.created_at,x.updated_at,x.source_id,x.`data`,x.`uuid`,x.source_entry_id
from
(select t.*,
(@num:=if(@group = `source_id`, @num +1, if(@group := `source_id`, 1, 1))) row_number
from (
select d.id,d.created_at,d.updated_at,d.source_id,d.`data`,d.`uuid`,d.source_entry_id
from `streams` a
JOIN `stream_filters` b
on b.stream_id=a.id
JOIN `filter_results` c
on c.filter_id=b.id
JOIN `entries` d
on d.id=c.entry_id
where a.id=?
) t
order by `source_id`,created_at desc
) as x
where x.row_number <= 10
ORDER BY x.created_at DESC
",self.id])
end

它在记录有限的本地环境中正常工作。我有 t2.micro,它有 2 个 Gib 内存来为应用程序提供服务。现在这个查询耗尽了我的全部内存,应用程序变得毛躁。有什么建议我怎样才能做得更好?我想在不增加机器尺寸的情况下解决这个问题。

最佳答案

我曾经遇到过类似的问题。带有 mysql 变量的解决方案一开始看起来很简洁,但很难优化。您的情况似乎是在进行全表扫描。

我建议先获取您要显示的来源。然后运行第二个查询,其中包含多个前 10 个选择,每个源一个,所有这些都与联合组合。

union top 10 select 将有一些重复语句,您可以使用 ruby​​ 轻松自动生成这些语句。

# pseudo code
sources = Entry.group(:source).limit(n)
sql = sources.map do |source|
"select * from entries where source = #{source} order by created_at limit 10"
end.join("\nunion all\n")

Entry.find_by_sql(sql)

关于mysql - Rails 选择每组前 n 条记录(内存泄漏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com