我有以下Activity
表:
ID TYPE SKU
=======================
1 create ABC
2 create DEF
3 destroy DEF
如何才能获得所有 create
事件的 destroy
事件?
执行Activity.where(type: 'create')
会给我1个ID和2个。
但我只想要第一行,因为id 2也有一个destroy事件。
答案 0 :(得分:3)
我想这应该可行
Activity.where('activities.type = ? AND activities.sku NOT IN
(SELECT sku from activities where type = ?)', 'create', 'destroy')
答案 1 :(得分:1)
如果你真的想使用有效记录,这会让你更接近:
class Activity < ActiveRecord::Base
scope :with_destroy, lambda { where(:action => 'destroy') }
scope :create, lambda {where(:action => 'create') }
scope :create_without_destroy, lambda {
create.where("sku not in (" << Activity.select(:sku).with_destroy.group(:sku).to_sql << ")")
}
end
生成的SQL:
> Activity.create_without_destroy
SELECT "activities".* FROM "activities"
WHERE "activities"."action" = 'create' AND (
sku not in (
SELECT
sku
FROM "activities"
WHERE "activities"."action" = 'destroy'
GROUP BY sku
))