我正在将管理系统从PHP迁移到Ruby On Rails。旧系统的一部分使用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
customer
表现在位于Customer
模型中,而customer_contact
现在位于CustomerCallback
模型中。我想使用rails构建一个类似的列表,最好不使用原始SQL。有大约10,000个客户记录,所以我现在想的方式(拉动所有客户,检查他们的最后一次联系,然后按顺序订购一个阵列)将会非常低效。
任何指针?
因此,它按照子女的最高日期订购客户列表,然后限制停止提取10,000条记录,如上面的SQL。
如果这很难理解,我会大肆宣传,但很难说出来
答案 0 :(得分:1)
由于这是自定义的,我建议使用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")