2014-09-21 144 views
-2

我已经给客户和产品下表查询多个表

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

,我希望获取匹配SalesPrice。我有点卡住,并会感谢任何帮助

+0

这是SQL中的基本连接查询。如果你想使用数据库,你应该学习SQL基础知识。 – 2014-09-21 13:30:38

+0

请关于'Rails'和'ActiveRecord'修复标签,并指定您使用的是哪种SQL。 – 2014-09-21 13:41:26

+0

请参阅:http://guides.rubyonrails.org/association_basics.html – 2014-09-21 16:59:49

回答

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> 
+0

虽然这是相关且正确的,但RoR中的ActiveRecord提供了更多的语义和“Rails”方法,可以使用AR查询语法执行此操作。 – 2014-09-21 16:58:22