Rails Arel相当于这个复杂的sql查询

时间:2012-11-27 23:57:19

标签: sql ruby-on-rails arel

这是原始逻辑

(scrape_datas = ScrapeData.find(
  :all, :conditions => 
  "artist_status = 'NOT_FOUND' 
   AND blacklisted = 1 
   AND extracted = 0 
   and not EXISTS(
     SELECT * FROM artist_name_suggestions where original = artist_name
   )

我能够更好地分割第一部分

scrape_datas = ScrapeData.where(
  :artist_status => 'NOT_FOUND',
  :blacklisted   => 1,
  :extracted     => 0
)

虽然在混合

中遇到“而不是EXISTS”查询时遇到问题
and not EXISTS(
  SELECT * FROM artist_name_suggestions where original = artist_name
)

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您可以提取简单的范围:

scope :not_found, where(:artist_status => 'NOT_FOUND')
scope :blacklisted, where(:blacklisted => 1)
scope :extracted, where(:extracted => 0)

然后添加一个查询方法(假设artist_name是一个scrape_datas列):

def self.no_suggestions
  scrape_datas = ScrapeData.arel_table
  suggestions = ArtistNameSuggestion.arel_table
  where(ArtistNameSuggestion.where(
    suggestions[:original].eq(scrape_datas[:artist_name])
  ).exists.not)
end

现在你可以这样做:

ScrapeData.not_found.blacklisted.extracted.no_suggestions