我试图解决性能问题,我们在大量的非顺序ID上运行WHERE IN子句。根据this和Performance MySQL的书籍,您可以通过创建一个有问题的临时表并加入您关心的表来加速性能。推迟使用ActiveRecord在MySQL中删除一个临时表
我有一个ActiveRecord::Base
类中的以下Rails代码:
def self.where_in(field, ids)
tmp_table = "tmp_table_#{SecureRandom.uuid.gsub('-', '_')}"
begin
# Create temporary table with one column
connection.execute("CREATE TEMPORARY TABLE #{tmp_table} (param INT NOT NULL PRIMARY KEY) ENGINE=Memory")
# Insert ids into the table (doesn't have to be ids)
vals = ids.map{|i| "(#{i})"}.join(", ")
connection.execute("INSERT INTO #{tmp_table} (param) VALUES #{vals};")
# Return the join relation which is the same as WHERE IN (...)
return self.joins("INNER JOIN #{tmp_table} on #{field} = #{tmp_table}.param").all
ensure
# Drop table after we're done...this is the problem
connection.execute("DROP TEMPORARY TABLE IF EXISTS #{tmp_table}")
end
end
但问题是,这创造依赖于我丢弃在保证声明的临时表存在的SQL语句。如果我删除了确保声明,它仍然可以正常工作,但临时表仍然存在。
鉴于此,我的问题是这样的:
我怎么会“推迟”这个表短大跌眼镜表名到背景上的工人在以后的时间下降的下落?
OR
我是安全的无法删除表,只是假设,连接池将收获的连接,从而删除表最后?