如何在rails3中运行此自定义复杂查询

时间:2012-08-20 11:58:21

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

如何在rake任务中运行以下查询?

DELETE FROM crawled_categories WHERE id NOT IN (
   SELECT id FROM (
       SELECT DISTINCT(site_id, parent_category, breadcrumb), max(id) AS id
       FROM crawled_categories 
       WHERE map_id is null
       GROUP BY site_id, parent_category, breadcrumb
   ) AS tmp
) AND map_id IS NULL

1 个答案:

答案 0 :(得分:0)

我尝试了以下代码并且工作正常:

ActiveRecord::Base.connection.execute("DELETE FROM crawled_categories WHERE id NOT IN ( SELECT id FROM ( SELECT DISTINCT(site_id, parent_category, breadcrumb), max(id) AS id FROM crawled_categories WHERE map_id is null GROUP BY site_id, parent_category, breadcrumb ) AS tmp ) AND map_id IS NULL")