2013-03-06 50 views
0

假設我有兩個型號,submissionhas_manysubmissionstate如何在Rails 3中重寫這個SQL查詢?

和表submissionstates有以下欄目:

id | submission_id | state_id | created_at 

和查詢

SELECT submission_id, state_id 
FROM submissionstates ss 
JOIN (
    SELECT MAX(created_at) as created_at 
    FROM submissionstates ss 
    GROUP BY submission_id 
) x 
ON ss.created_at = x.created_at 
WHERE state_id = 0 
+0

上查詢RoR的文檔,應該可以幫助您http://guides.rubyonrails.org/active_record_querying.html – 2013-03-06 15:37:30

+1

參考 - http://stackoverflow.com/questions/7016422/how-to-convert-sql-query-to-rails-active-record-query – 2013-03-06 15:44:49

回答

1

像SAURABH給的鏈接,你最終把你的SQL片段放入rails查詢方法中;像這樣

list = SubmissionState.select("submission_id, state_id") 
    .where(:state_id => 0) 
    .joins(" 
    JOIN (
     SELECT MAX(created_at) as created_at 
     FROM submissionstates ss 
     GROUP BY submission_id 
    ) x 
    ON ss.created_at = x.created_at 
    ") 

puts list.length 

是在這一點上誠實,你可能會更好只是用的find_by_sql

sql = " 
    SELECT submission_id, state_id 
    FROM submissionstates ss 
    JOIN (
    SELECT MAX(created_at) as created_at 
    FROM submissionstates ss 
    GROUP BY submission_id 
) x 
    ON ss.created_at = x.created_at 
    WHERE state_id = ? 
    AND some_other_value = ? 
" 

list = SubmissionState.find_by_sql([sql, 0, 'something-else']) 
puts list.length 

注意:一旦你開始使用連接或的find_by_sql鐵軌就像它給你的對象回來,但真的它們將包含在SELECT子句和回報的find_by_sql定義的任何屬性的所有屬性爲字符串,可以是惱人

+0

嗯..我只是想知道,哪一個更有效率? 'find_by_sql'或'Active Record Query Interface'? – 2013-03-06 16:26:57

+0

「我只是想知道哪一個更高效?」 >我的猜測是一樣的 - 你可以下降到一個較低的水平,並取回一個哈希代替 - http://blog.daniel-azuma.com/archives/216 – house9 2013-03-06 16:57:58