我能夠運行這個查詢生成區域的哈希值和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的:問題
感謝
結果是一樣的,如果我包括這個選擇方法 –
'.select('region.name IS 0')'它工作嗎? – itsnikolay