新手问题 数据怎么查询才能优化查询速度

liguangsong · November 17, 2015 · Last by liguangsong replied at November 19, 2015 · 1947 hits

我现在有一个用户表里面有个学历这个属性,然后我有一个文章表,use:has_many: articles 我应该怎么去实现查找全部发布者学历大于本科的文章 我现在是这么做的

Article.where(opend_id: user.where('大于本科').pluck(article_id:)).order("updated_at desc").paginate(:page => params[:page], :per_page => 8)

但是感觉如果数据多了,感觉这个过程会很浪费时间不知道怎么做才好

想快就在 articles 加字段 Article.where('大于本科')

否则 Article.includes(:user).where("users.大于本科")

http://apidock.com/rails/ActiveRecord/QueryMethods/includes

@nine 在 articles 加上什么字段 能具体说明下么

3 Floor has deleted

@nine Note.includes(:user_information).where("user_information.degree" => '专科' ) 出现错误

Mysql2::Error: Unknown column 'user_information.degree' in 'where clause': SELECT `notes`.`id` AS t0_r0, `notes`.`content` AS t0_r1, `notes`.`created_at` AS t0_r2, `notes`.`updated_at` AS t0_r3, `notes`.`img` AS t0_r4, `notes`.`publisher_id` AS t0_r5, `user_informations`.`id` AS t1_r0, `user_informations`.`name` AS t1_r1, `user_informations`.`sex` AS t1_r2, `user_informations`.`age` AS t1_r3, `user_informations`.`work` AS t1_r4, `user_informations`.`height` AS t1_r5, `user_informations`.`Nickname` AS t1_r6, `user_informations`.`image` AS t1_r7, `user_informations`.`created_at` AS t1_r8, `user_informations`.`updated_at` AS t1_r9, `user_informations`.`stars` AS t1_r10, `user_informations`.`contact` AS t1_r11, `user_informations`.`degree` AS t1_r12, `user_informations`.`address` AS t1_r13 FROM `notes` LEFT OUTER JOIN `user_informations` ON `user_informations`.`name` = `notes`.`publisher_id` WHERE `user_information`.`degree` = '专科'

@liguangsong 他说的在 article 加字段,是说把学历这个字段加到 article 上,搜索的时候直接 Article.where('大于本科') 第二个应该是这么写吧 Note.includes(:user_information).where("user_informations.degree = ?" , '专科' )

@tianlitao 这样写也有错误

Mysql2::Error: Unknown column 'user_informations.degree本科' in 'where clause': SELECT `notes`.* FROM `notes` WHERE (user_informations.degree本科)

如果是 UserInformation.includes(:notes).where("notes.content" => "s" ) 就是能用的

#4 楼 @liguangsong where("user_information.degree" => '专科' ) include 单数,而表名应该用复数 where("user_informations.degree" => '专科' )

写联表查询都会比现在这种嵌套的子查询快很多

9 Floor has deleted
10 Floor has deleted

joins or includes 不谢 😄

@nine 你的方法是对的,是我后面排序写的是.order("updated_at desc") 不对,而应该写成.order(updated_at: :desc)

You need to Sign in before reply, if you don't have an account, please Sign up first.