2013-10-15 39 views
1

我能夠運行這個查詢生成區域的哈希值和group by答案(包括零計數):的Rails:組和計數SQL查詢包括零的

Region.includes(:answers).group("regions.region").count("answers")

生產:

{"blar"=>0, "East"=>0, "East Midlands"=>11, "London"=>8, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>89, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0} 

但是,當我想要某個特定問題的結果(包括計數零)時,它只顯示帶有答案的區域的散列。

查詢:

Region.includes(:answers).where("answers.question_id = 14").group("regions.region").count("answers") 

生產:

{"East Midlands"=>3, "London"=>1, "Rest of World"=>4} 

我理解查詢將只選擇question_id答案,所以這給定的輸出,但我已經嘗試過許多不同的查詢(包括左外連接)並且無法獲得所需的結果。

參考:

地區的has_many:回答

答belongs_to的:區域

答belongs_to的:問題

感謝

回答

1

任何有興趣,我可以通過添加SQL來解決這個爲空或where子句像這樣:

Region.includes(:answers).where("answers.id IS NULL OR answers.question_id = 14").group("regions.region").count("answers") 

生產:

{"blar"=>0, "East"=>0, "East Midlands"=>1, "London"=>0, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>4, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0} 

可能不是最好的方式,但它做了這個工作

0

添加選擇具有空值顯式的,像下面:

Region.outer_joins(:answers).select('region.name IS NULL'). 
+0

結果是一樣的,如果我包括這個選擇方法 –

+0

'.select('region.name IS 0')'它工作嗎? – itsnikolay