Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 查询处理时间较长。检索数据时出现性能问题_Mysql_Ruby On Rails_Activerecord_Database Performance - Fatal编程技术网

Mysql 查询处理时间较长。检索数据时出现性能问题

Mysql 查询处理时间较长。检索数据时出现性能问题,mysql,ruby-on-rails,activerecord,database-performance,Mysql,Ruby On Rails,Activerecord,Database Performance,我有一些复杂的模型设计,它们之间有很多联系。 这是模型设计 用户模型 class User < ActiveRecord::Base has_many :records validates :email, presence: true end 处理时间非常短,只有1000条记录,所以我不确定我正在做的是错误的查询还是其他什么 应用程序正在使用MySQl作为数据库 Completed 200 OK in 2338ms (Views: 0.5ms | ActiveRecord: 445.

我有一些复杂的模型设计,它们之间有很多联系。 这是模型设计

用户模型

class User < ActiveRecord::Base
has_many :records

validates :email, presence: true

end
处理时间非常短,只有1000条记录,所以我不确定我正在做的是错误的查询还是其他什么

应用程序正在使用MySQl作为数据库

Completed 200 OK in 2338ms (Views: 0.5ms | ActiveRecord: 445.5ms)

在我看来,你似乎在制造许多不必要的查询。您可以使用正确的记录查询单个记录类型,这将导致在子句中生成一个,并在数据库端执行,而不是拉出记录并对其进行迭代(这本应使用
。查找每个
而不是
。每个
)。如果我正确理解了您的模式,您可以获得如下相同的数据(AR 4.1.1):

这将导致总共3个查询。您可以按如下方式使代码更清晰:

r = [RecordTypeStudent, RecordTypeEmployee, RecordTypeOther].flat_map do |type|
  type.where(record: Record.where(user_id: 1)).to_a
end
如果您想进一步减少查询数量,可以通过这些表之间的
UNION
获取数据,但我认为没有必要这样做


我猜它就在问题的文本中,但是在
记录
模型中,那些
有许多
必须用复数参数指定,否则它将不起作用

谢谢你的回答,很抱歉我忘了在记录模型中输入复数,但这不起作用,因为它抱怨“in/ALL/ANY subquery”中的未知列“record\u type\u students.records”你使用的是什么版本的Rails(以及AR)?如果您使用的是旧版本,它可能无法识别关联。请尝试
.where(record\u id:record.where(user\u id:1))
。我使用的是rails 4.0.2和随后的ARYeah,它太旧了,无法识别关联。只需尝试在where语句中使用
record\u id
而不是
record
。感谢您的输入,我已经解决了这个问题,但我有一个问题,您知道一些快速构建json的库吗?我正在使用Jbuilder和multijson,10000条记录需要6秒钟。。。
@records = Record.where(:user_id => 1)
@r = []
@records.each do |m|
  if !r.record_type_students.empty?
    @r += r.record_type_students
  end
  if !r.record_type_other.empty?
    @r += r.record_type_others
  end
  if !r.record_type_employees.empty?
    @r += r.record_type_employees
  end
end
Completed 200 OK in 2338ms (Views: 0.5ms | ActiveRecord: 445.5ms)
record = Record.where(user_id: 1)
r = []
r += RecordTypeStudent.where(record: record).to_a
r += RecordTypeEmployee.where(record: record).to_a
r += RecordTypeOther.where(record: record).to_a
r = [RecordTypeStudent, RecordTypeEmployee, RecordTypeOther].flat_map do |type|
  type.where(record: Record.where(user_id: 1)).to_a
end