加入不工作正常

问题描述:

我得到了下面的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

连接()的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