SQL选择具有特定类型汽车的用户

时间:2016-06-02 09:31:16

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

客户有很多车 每辆车都属于ManufacturingPlant
ManufacturingPlant有一个名为:country

的属性

如何找到汽车不是在印度制造的客户?

Customer.joins(:cars).where.not(cars: {manufacturing_plant_id: ManufacturingPlant.find_by_country("india").id})

在这种情况下,如果用户拥有在中国和印度制造的汽车,用户不应该出现在结果中,因为他在印度工厂生产汽车。但是通过上面的查询确实如此。

另外,我们如何编写一个不使用任何数组操作的查询,例如IN?

3 个答案:

答案 0 :(得分:2)

嘿,你可以这样试试:

有关更多信息,请参阅类似的my post

Customer.joins({cars: [:manufacturing_plant]}).group("cars.customer_id").having("SUM(CASE WHEN manufacturing_plant.country = 'india' THEN 1 
        ELSE 0 
        END) = 0")

答案 1 :(得分:1)

通过user_id和""进行分组并进行SQL操作。 plant_id检查" india_make"国旗可以工作。 SQL就像这样

select user_id, sum(CASE WHEN car.plant_id in [1,2, ..] THEN 1 ELSE 0 END) as if_india_made
from users, cars
where user.user_id = car.user_id
group by user.id
having if_india_made = 0;

不确定你是否可以把它放进去"很好" ActiveRecord代码虽然

here这在SQL中使用SQL Fiddle进行了说明(没有连接表,但概念应该是明确的。Same,其中包含句子

答案 2 :(得分:0)

您可以尝试使用印度或中国制造的汽车首先找到所有客户

class Customer
  scope :with_cars_made_in, -> (countries) { joins(cars: :manufacturing_plant).where("manufacturing_plants.country" => countries) }

然后,不在印度或中国制造汽车的客户就像

@customers = Customer.where.not(id: Customer.with_cars_made_in(["China", "India"]).pluck("customers.id"))