简体   繁体   English

通过定制选择导轨订购

[英]Order by custom select rails

I am in the process of moving our admin system over from PHP to Ruby On Rails. 我正在将我们的管理系统从PHP迁移到Ruby On Rails。 There was a part of the old system that used SQL to build a list of customers and then order them by the time at which they was last contacted: 旧系统中有一部分使用SQL来建立客户列表,然后在上次联系客户时对其进行排序:

    SELECT 
      `customer`.*, (
        SELECT MAX(`date`)
        FROM `customer_contact`
        WHERE `customer`.`Customer_ID`=`customer_contact`.`customer_id`
        ORDER BY `date` DESC
        LIMIT 1
      ) AS `last_contacted`
    FROM
      `lead_details`
    GROUP BY `customer`.`Company_Name`
    ORDER BY `last_contacted`
    LIMIT 50

The customer table is now in the Customer model and the customer_contact is now in a CustomerCallback model. customer表现在处于Customer模型中,而customer_contact现在处于CustomerCallback模型中。 I want to build a similar list using rails and preferably without using that raw SQL. 我想使用rails构建一个类似的列表,最好不要使用该原始SQL。 There's about 10,000 customer records so the way I've figured to do it at the moment (pull all customers, check their last contact and then order an array by that) would be incredibly inefficient. 大约有10,000个客户记录,所以我现在想做的方式(拉动所有客户,检查他们的最后联系人,然后订购一个数组)会非常低效。

Any pointers? 有指针吗?

So it orders a list of customers by the highest date of its children and then limits that to stop pulling in 10,000 records like the SQL above. 因此,它按其子项的最高日期排序一个客户列表,然后限制该列表以停止拉入10,000条记录,例如上面的SQL。

I apoligise if this is tough to understand, but it's hard to put into words 如果这很难理解,我会公开声明,但是很难说出来

Since that's so customized, I would suggest using select_rows , like: 由于这是自定义的,因此建议使用select_rows ,例如:

customers = Customer.connection.select_rows("SELECT 
    `customer`.*, (
      SELECT MAX(`date`)
      FROM `customer_contact`
      WHERE `customer`.`Customer_ID`=`customer_contact`.`customer_id`
      ORDER BY `date` DESC
      LIMIT 1
    ) AS `last_contacted`
  FROM
    `lead_details`
  GROUP BY `customer`.`Company_Name`
  ORDER BY `last_contacted`
  LIMIT 50")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM