简体   繁体   中英

Why is my Active Record Query returning different results than my raw SQL

I'm trying to do a query using an INNER JOIN, COUNT, and GROUP BY to order my tags by the amount of taggings they have, and include the count as a part of the result. Raw sql returns the actual Count that I'm grouping by whereas active record is not.

Tag.joins(:taggings).select('tags.id, tags.name, COUNT(taggings.note_id) as count').group('tags.id').order('count desc').to_a

returns

[#<Tag:0x007fa663be15e8 id: "d40dac2e-917b-4078-dfdf-47c1a6d43c72", name: "name1">,
 #<Tag:0x007fa663be0918 id: "aa5d0f22-b6ad-46b0-sasa-0e2300ddc0fb", name: "name2">,
 #<Tag:0x007fa663bead28 id: "7880318b-9bdc-48f5-a93c-b4b393f15d8b", name: "name3">,
 #<Tag:0x007fa663beb228 id: "77c6ef97-f3ce-43be-vghf-45bb897fe4a7", name: "name4">,
...

But when I turn this active record query into raw SQL I get the response I'm actually looking for.

sql = Tag.joins(:taggings).select('tags.id, tags.name, COUNT(taggings.note_id) as count').group('tags.id').order('count desc').to_sql
ActiveRecord::Base.connection.execute(sql).to_a

returns

{"id"=>"d40dac2e-917b-4078-dfdf-47c1a6d43c72", "name"=>"name1", "count"=>"36"},
 {"id"=>"aa5d0f22-b6ad-46b0-sasa-0e2300ddc0fb", "name"=>"name2", "count"=>"24"},
 {"id"=>"7880318b-9bdc-48f5-a93c-b4b393f15d8b", "name"=>"name3", "count"=>"12"},
 {"id"=>"77c6ef97-f3ce-43be-vghf-45bb897fe4a7", "name"=>"name4", "count"=>"10"},
...

I think using straight up active record would be cleaner. Any suggestions on how I could improve this query?

Thank you.

Turns out I AM getting the correct results with active record. I can call #count on each instance which yields the correct result even though it's not visibly there in the terminal response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM