数据库
首页 > 数据库> > 如何将多个Rails SQL查询合并到Rails中的单个查询中?

如何将多个Rails SQL查询合并到Rails中的单个查询中?

作者:互联网

在我的rails代码中,我需要基于记录的日期和记录已收到的投票的组合在表上运行查询.我像在rails中那样完成它:

if params[:sort_by] == "default"
    objs1 = class_name.where("created_at between '#{Date.today - 7}' and '#{Date.today}' and net_votes > 0").order("net_votes DESC")
    objs2 = class_name.where("created_at between '#{Date.today - 30}' and '#{Date.today - 7}' and net_votes > 0").order("net_votes DESC")
    objs3 = class_name.where("created_at between '#{Date.today - 90}' and '#{Date.today - 30}' and net_votes > 0").order("net_votes DESC")
    objs4 = class_name.where("created_at < '#{Date.today - 90}' and net_votes > 0").order("net_votes DESC")
    objs = objs1 + objs2 + objs3 + objs4

除了效率,我不能对组合查询结果使用分页,更不用说代码很丑陋了.正确的方法是什么?

提前致谢.

解决方法:

将命令用于排序逻辑,而不是在以下位置:

order_by_sql = <<-SQL
CASE WHEN created_at between '#{Date.today - 7}' and '#{Date.today}' THEN 1
     WHEN created_at between '#{Date.today - 30}' and '#{Date.today - 7}' THEN 2
     WHEN created_at between '#{Date.today - 90}' and '#{Date.today - 30}' THEN 3
     ELSE 4
END
SQL

objs = class_name.where('net_votes > 0').order(order_by_sql)

标签:postgresql,rails-activerecord,ruby-on-rails,sql,mysql
来源: https://codeday.me/bug/20191030/1964467.html