2017-02-11 73 views
0

條款我有這樣的SQL查詢:SQL與軌道

WITH excluded_authors as 
    (SELECT author_id from authors_books) 
SELECT authors.* from authors 
    WHERE authors.id not in 
    (SELECT author_id FROM excluded_authors) 

這裏的目標是讓所有有沒有書的作者。 ?

如何制定在軌該查詢(而不是將其複製到find_by_sql

編輯

我嘗試這樣做:

Author.where.not("\"authors\".\"id\" in \"authors_bilios\".\"authors_id\"") 
+0

雙查詢我想'find_by_sql'其工作和與'where.not'不工作。 'find_by_sql'可能不是最令人滿意的方式。這就是爲什麼你低估了這個問題嗎? – thiebo

+0

在stackoverflow它預計你顯示你已經嘗試過,然後尋求幫助。這樣你會得到更好的幫助。 – Iceman

+1

你是對的。我編輯了我的問題來展示我所做的。我有一些工作,但只是想知道是否有更好的方法。 – thiebo

回答

1

這可能是最簡單的方法,它雖然不能很好地擴展,但要注意的是,如果你有成千上萬或數百萬行的話,那麼

author_ids = AuthorsBooks.pluck(:author_id) 
@authors = Author.where('id not in (?)', author_ids) 

編輯: 可避免與

@authors = Author.where('id not in (select author_id from authors_books)') 
+0

謝謝。不會有成千上萬的行,但數百個是。我想避免雙重查詢。但我猜''with'子句本身就是一個雙重查詢。 – thiebo

+0

那麼,你可以避免雙重查詢,看看我的編輯。 – Iceman

+1

而且速度也更快!對於您的解決方案,帶有「with」子句和「ActiveRecord:6.7ms」的查詢使用「ActiveRecord:10.3ms」。 – thiebo