我試圖解決性能問題,我們在大量的非順序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
我是安全的無法刪除表,只是假設,連接池將收穫的連接,從而刪除表最後?