这两个查询在rails 3.2.12中是否相同?

时间:2013-04-25 19:19:37

标签: sql ruby-on-rails ruby-on-rails-3 arel

我们需要在rails应用中检索logs的{​​{1}}。简体中文的条件是customer_comm_record的日志基于:

customer comm record

#1的SQL代码可以是(#1. the sales_id in customer comm record's customers is equal to current user id #2. the sales_id in customer comm record's customer's project is equal to the current user id. ):

SQL#1

#2的SQL代码可以是(Log.joins(:customer_comm_record =>:customer).where('customers.sales_id = ?', session[:user_id]) ):

SQL#2

以下是我们在一行中提出的问题(Log.joins(:customer_comm_record =>{ :customer => :projects}).where('projects.sales_id = ?', session[:user_id]) ):

SQL#3

上面Log.joins(:customer_comm_record =>{ :customer => :projects}).where('customers.sales_id = ? OR projects.sales_id = ?', session[:user_id], session[:user_id]) 返回的SQL代码是(将session [:user_id]替换为1):

rails console

问题是天气 SELECT "logs".* FROM "logs" INNER JOIN "customer_comm_records" ON "customer_comm_records"."id" = "logs"."customer_comm_record_id" INNER JOIN "customers" ON "customers"."id" = "customer_comm_records"."customer_id" INNER JOIN "projects" ON "projects"."customer_id" = "customers"."id" WHERE (customers.sales_id = 1 OR projects.sales_id = 1) 。有人可以回答这个问题吗?如果不是,那么什么是正确的?感谢。

1 个答案:

答案 0 :(得分:2)

唯一的区别是:

  • 第一种方法将返回重复的条目,其中customer和project的sales_id都与用户ID匹配。
  • 第二种方法可能不会返回具有匹配的sales_id的客户没有项目的记录(该客户没有projects.customer_id)。

最后的区别仅在客户不一定有任何项目时才有意义。否则,第二种方法更好,因为它避免了处理重复。

如果客户并不总是有项目,那么一个简单的解决方法就是使用includes代替joins

Log.includes(:customer_comm_record =>{ :customer => :projects}).
    where('customers.sales_id = :id OR projects.sales_id = :id', id: session[:user_id])

这将强制LEFT JOIN并将返回客户,无论他们是否与项目相关联。