ruby-on-rails - Rails 迁移以添加索引到 2 列之间的差异

标签 ruby-on-rails postgresql indexing database-migration

在我的 Ruby on Rails 应用程序中,我有一个模型 Message,它有一个 created_at 列和一个 status_updated_at 列。它们都是日期时间。

为了加快查询速度,例如 Message.where(status: 'delivered', account_id: 11).where('status_updated_at - created_at >= ?', "180 seconds"),我想为列 status_updated_atcreated_at 之间的差异添加索引。

我试过这段代码:

class AddMessageIndicesForDashboard < ActiveRecord::Migration[5.1]
  def change
    add_index :messages, [:status, :account_id, :created_at, "(status_updated_at-created_at)"], name: 'dashboard_delivery_time_index'
  end
end

这导致 PG::UndefinedColumn: ERROR: column "status_updated_at-created_at"does not exist

奇怪的是,假设我只想通过执行 add_index :messages, "(status_updated_at-created_at)", name: 'dashboard_delivery_time_index' 将索引添加到 status_udpated_at - created_at ,它将起作用。

有什么建议吗?谢谢!

最佳答案

也许试试

add_index :messages, "(status_updated_at-created_at)", name: 'dashboard_delivery_time_index'  

PostgreSQL(9.1) 11.7. Indexes on Expressions .

The syntax of the CREATE INDEX command normally requires writing parentheses around index expressions... The parentheses can be omitted when the expression is just a function call...

因为你想使用表达式而不是函数,所以额外的括号应该根据文档来完成。

关于ruby-on-rails - Rails 迁移以添加索引到 2 列之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484722/

相关文章:

mysql - Bundle Install 不会安装带有 Ruby 1.9.3、Rails3 和 Mac Mountain Lion 的 mysql2 gem

postgresql - 我们可以在存储过程中调用触发器函数吗

sql - Postgre/SQL 递归查询

indexing - Elasticsearch:在我的英语分析器上添加同义词过滤器

optimization - 优化我的 mysql 查询以使用索引进行排序

ruby-on-rails - 如何获取模型中图像变体的 url(在 Controller / View 之外)?主动存储

ruby-on-rails - Rails,对模型所有实例的属性求和

javascript - Rails - 单击 link_to 展开表行

SQL 查询以选择第 1 列中的值对,这些值与第 2 列中的两个模式之一匹配

arrays - 在 MATLAB 中使用矩阵进行矩阵索引