Rails如何通过连接自己获取表结果?

时间:2014-01-10 22:57:51

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我有以下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事件。

2 个答案:

答案 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
))