客户has_many轿车
每辆车都属于ManufacturingPlant
ManufacturingPlant有一个名为:country的属性
如何找到不在印度制造的客户?
Customer.joins(:cars).where.not(cars: {manufacturing_plant_id: ManufacturingPlant.find_by_country("india").id})在这种情况下,如果用户有中国和印度制造的汽车,用户就不应该出现在结果中,因为他有一辆在印度工厂生产的汽车。但是有了上面的查询,它就做到了。
另外,我们如何编写不使用任何数组操作(例如IN )的查询?
发布于 2016-06-02 10:03:13
嘿,你可以试试这个方法:
有关更多信息,请参考一些类似的我的职位
Customer.joins({cars: [:manufacturing_plant]}).group("cars.customer_id").having("SUM(CASE WHEN manufacturing_plant.country = 'india' THEN 1
ELSE 0
END) = 0")发布于 2016-06-02 09:56:57
一些按user_id和“plant_id”进行分组以检查"india_make“标志的SQL操作可以工作。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代码中。
这里使用SQL (没有连接表,但概念应该很清楚)说明了这一点。带套管的相同的内有子句
发布于 2016-06-02 09:43:36
你可以先找一辆印度制造的车或中国制造的车去找所有的顾客。
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"))https://stackoverflow.com/questions/37587896
复制相似问题