查询多个表

时间:2014-09-21 13:24:43

标签: sql ruby-on-rails activerecord

我有以下表格

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

鉴于客户和产品,我想获取匹配的SalesPrice。我有点被困,希望得到任何帮助

1 个答案:

答案 0 :(得分:1)

这是您可能没有使用的MSSQL,但它应该有所帮助。只要从你所知道的事情中走出来,直到你得到你不知道的东西。

SELECT sp.id, sp.margin
FROM SalesPrices sp
LEFT OUTER JOIN ProductSalesPrices ps
    ON sp.id = ps.sales_price_id
LEFT OUTER JOIN CustomerPriceRelations cr
    ON ps.sales_price_id = cr.sales_price_id
LEFT OUTER JOIN Customers c
    ON cr.customer_id = c.id
WHERE c.id = <your customer id> AND ps.product_id = <your product id>