【问题标题】:Complex select based on two has_many associations基于两个 has_many 关联的复杂选择
【发布时间】:2016-09-27 10:06:33
【问题描述】:

我有以下型号

帐户

has_many :orders
has_many :account_brands, dependent: :destroy
has_many :brands, through: :account_brands

品牌

  has_many :account_brands, dependent: :destroy
  has_many :accounts, through: :account_brands
  has_many :orders

订购

belongs_to :account
belongs_to :brand

现在我想选择所有与该帐户没有关联的品牌订单的帐户。我可以通过循环和检查每个特定品牌来做到这一点,但效率非常低。无法在一次 SQL 调用中了解如何做到这一点?

只是为了澄清和改写:

我想要所有具有当前未与该帐户关联的品牌的订单的帐户

Account1 have brands A,B,C    
Account2 have brands A,B,C


Account1 have order with the brand D -> want this account to be selected
Account2 have order with the brand C -> doesn't care about this one

【问题讨论】:

  • 您能说出您所说的“所说”帐户是什么意思吗?
  • 所以据我了解,您是否想要所有有品牌订单的帐户?
  • 抱歉不是我的母语,刚刚用示例更新了我的问题
  • 我已经更新了答案。请检查
  • SELECT * FROM accounts JOIN orders ON accounts.id = orders.account_id WHERE accounts.brand_id <> order.brand_id,这是你在 Rails 中需要的吗?

标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord


【解决方案1】:

要找出有与指定帐户无关的品牌订单的帐户,请尝试以下查询,

Account.joins(:brands).joins("LEFT JOIN orders ON (orders.account_id = accounts.id AND orders.brand_id != brands.id)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多