簡體   English   中英

Rails Arel等效於此復雜的SQL查詢

[英]Rails Arel equivalent of this complex sql query

這是原始邏輯

(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
)

盡管在將“ not not EXISTS”查詢混入中時遇到問題

and not EXISTS(
  SELECT * FROM artist_name_suggestions where original = artist_name
)

謝謝!

首先,您可以提取簡單的范圍:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM