【问题标题】:Rails exclusive relation SQL selectRails 排他关系 SQL 选择
【发布时间】:2020-07-20 23:10:43
【问题描述】:

我有这样的问题:

假设我有两个模型,Person 和 House,其中一个 Person 有多个 House,每个 House 属于一个 Person。

假设房屋可以是红色、绿色或蓝色。如果相关,假设每个人至少有 1 个房子。

如何在 Person 上写一个范围来选择没有红房子的人?

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    你试过了吗

    Person.where(id: House.not.where(color: 'red').pluck(:person_id).uniq)
    

    或其他方式

     Person.left_joins(:houses).where("houses.color <> ?", 'red').uniq
    

    【讨论】:

      【解决方案2】:

      在 sql 数据库情况下。如果您的 Person 表是列 people。 用红色选择不在 House 表中的人。

      select * from Person where people not in (select distinct people from House where color ='red')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2014-02-22
        • 2014-08-12
        相关资源
        最近更新 更多