【问题标题】:Query multiple tables查询多个表
【发布时间】:2014-09-21 13:24:42
【问题描述】:

我有以下表格

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

给定一个客户和一个产品,我想获取匹配的 SalesPrice。我有点卡住了,希望有任何帮助

【问题讨论】:

  • 这是 SQL 中的基本连接查询。如果你想使用数据库,你应该学习 SQL 基础。
  • 没有关于 RailsActiveRecord 的问题请修复标签并指定您使用的 sql 类型。

标签: sql ruby-on-rails activerecord


【解决方案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>

【讨论】:

  • 虽然这是相关且正确的,但 RoR 中的 ActiveRecord 使用 AR 查询语法提供了更多语义和“Rails”方式。
猜你喜欢
  • 2011-08-14
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多