我需要幫助將此SQL轉換爲ActiveRecord查詢。對Rails和SQL的相同查詢返回不同的結果
SELECT
MAX(total_sales.start_date) AS maximum_start_date,
customers.external_id, product_categories.external_id AS product_category_id
FROM
total_sales
INNER JOIN
customers
ON
customers.id = total_sales.customer_id
LEFT JOIN
product_categories
ON
product_categories.id = total_sales.product_category_id
WHERE
(customers.organization_id = 1)
GROUP BY
customers.external_id,
product_categories.external_id
我試着做
TotalSales.joins(:customer).includes(:product_category).
where("customers.organization_id = ?", 1).
group("customers.external_id, product_categories.external_id").
maximum(:start_date)
和它產生幾乎我想要的查詢。這是它產生:
SELECT
MAX("total_sales"."start_date") AS maximum_start_date,
customers.external_id, product_categories.external_id AS customers_external_id_product_categories_external_id
FROM
"total_sales"
INNER JOIN "customers" ON
"customers"."id" = "total_sales"."customer_id"
LEFT OUTER JOIN "product_categories" ON
"product_categories"."id" = "total_sales"."product_category_id"
WHERE
(customers.organization_id = 1)
GROUP BY
customers.external_id, product_categories.external_id
但這返回on Rails的:
=> {"DIA"=>Wed, 01 Jan 2014, "MES"=>Wed, 01 Jan 2014, nil=>Wed, 01 Jan 2014}
如果我運行DB控制檯上查詢,它返回
"2014-01-01";"CLIENTE.1";"DIA"
"2014-01-01";"CLIENTE.1";"MES"
"2014-01-01";"CLIENTE.1";""
"2014-01-01";"CLIENTE.10";"DIA"
"2014-01-01";"CLIENTE.10";"MES"
"2014-01-01";"CLIENTE.10";""
"2014-01-01";"CLIENTE.100";"DIA"
"2014-01-01";"CLIENTE.100";"MES"
...
,這就是我想要的。在數據庫控制檯上它可以工作,但在Rails上它卻不行。 :(
這裏是工作的查詢的例子:http://sqlfiddle.com/#!9/7a6d1/1/0。這同樣不適用於Rails .. –
猜測它是外部左連接和左連接產生的行爲。看看:http://stackoverflow.com/questions/8025429/how-can-i-do-a-left-outer-join-using-rails-activerecord另請看:http://www.codeproject.com/文章/ 33052/Visual-Representation of SQL-Joins一種方法可能是在獲取記錄後刪除位置並進行過濾,具體取決於記錄集大小 – Mircea
使用或不使用OUTER的查詢都會在數據庫上生成所需的輸出安慰。看起來問題在於AR如何通過散列來改變它。 –