2014-09-21 64 views
1

我得到了下面的SQL,我試圖將其轉換成活動記錄查詢方法加入不工作正常

我有以下表

Customers (id, name) 
CustomerPriceRelations (customer_id, sales_price_id) # jointable 
SalesPrices (id, margin) 
ProductSalesPrices (product_id, sales_price_id) # jointable 

,我試圖執行下面的查詢

SELECT sp.id, sp.margin_percentage 
        FROM sales_prices sp 
        LEFT OUTER JOIN carrier_product_Sales_Prices ps 
         ON sp.id = ps.sales_price_id 
        LEFT OUTER JOIN Customer_Price_Relations cr 
         ON ps.sales_price_id = cr.sales_price_id 
        LEFT OUTER JOIN Customers c 
         ON cr.customer_id = c.id 
        WHERE c.id = 2 AND ps.carrier_product_id = 3 

我試過使用連接方法,但結果從來沒有加入由於某種原因,任何幫助嗎?

SalesPrice.joins(:carrier_products, :customers).where(customer_id: 2, carrier_product_id: 3) 
+0

「結果永遠不會加入」結果是什麼?你需要更具體地瞭解什麼是和不在工作。 – 2014-09-21 15:16:47

+0

當我加入SalesPrice表中的表時,沒有新字段被添加到結果 – Tarlen 2014-09-21 15:22:52

回答

0

連接()的Rails標準行爲是INNER JOIN,而不是LEFT OUTER JOIN。 INNER JOIN意思是,除非有匹配,否則連接的兩邊都不會出現。如果要使用LEFT OUTER JOIN,則需要明確定義它:

SalesPrice.joins("LEFT OUTER JOIN carrier_product_Sales_Prices ps ON sales_prices.id = ps.sales_price_id"). 
      joins("LEFT OUTER JOIN Customer_Price_Relations cr ON ps.sales_price_id = cr.sales_price_id"). 
      joins("LEFT OUTER JOIN Customers c ON cr.customer_id = c.id"). 
      where("cr.customer_id = ? and carrier_product_id = ?", 2, 3) 
+0

,就像我自己的查詢一樣,這會返回'PG :: UndefinedColumn:ERROR:列sales_prices.customer_id不存在'。顯然它尋找SalesPrice上的customer_id列而不是聯接表,我該如何解決這個問題? – Tarlen 2014-09-21 17:02:05

+0

我用可能反映您需要的內容更新了代碼。 – 2014-09-21 17:21:09

+0

甜蜜,這是有效的,但你能解釋爲什麼這個工作,而不是另一個?非常感謝 – Tarlen 2014-09-21 17:24:12