RoR中多列的索引 [英] Index on multiple columns in RoR
问题描述
我正在执行功能来跟踪用户阅读的文章。
I'm implementing functionality to track which articles a user has read.
create_table "article", :force => true do |t|
t.string "title"
t.text "content"
end
这是我到目前为止的迁移:
This is my migration so far:
create_table :user_views do |t|
t.integer :user_id
t.integer :article_id
end
将始终查询user_views表以查找这两列,从不只有一列。我的问题是我的索引应该如何。这些表的顺序有差异,应该有更多的选择吗?我的目标数据库是Postgres。
The user_views table will always be queried to look for both columns, never only one. My question is how my index should look like. Is there a difference in the order of these tables, should there be some more options to it or whatever. My target DB is Postgres.
add_index(:user_views, [:article_id, :user_id])
谢谢。
更新:
因为只在两列中包含相同值的一行可能存在(因为在知道user_id HAS是否读取article_id)时,应该考虑:unique选项吗?如果我没有误会,这意味着我不必自己做任何检查,只要每次用户访问一篇文章就插入一个。
UPDATE:
Because only one row containing the same values in both columns can exist (since in knowing if user_id HAS read article_id), should I consider the :unique option? If I'm not mistaken that means I don't have to do any checking on my own and simply make an insert every time a user visits an article.
推荐答案
索引中的顺序很重要。
- 先选择最有选择性的字段,即缩小的字段行数最快。
- 只有从开始开始使用序列中的列,才会使用索引。即如果您在
[:user_id,:article_id]
上进行索引,则可以在user_id
或user_id AND article_id
,但不在article_id
。
- Put the most selective field first, i.e. the field that narrows down the number of rows fastest.
- The index will only be used insofar as you use its columns in sequence starting at the beginning. i.e. if you index on
[:user_id, :article_id]
, you can perform a fast query onuser_id
oruser_id AND article_id
, but NOT onarticle_id
.
您的迁移 add_index
行应该如下所示:
Your migration add_index
line should look something like this:
add_index :user_views, [:user_id, :article_id]
有关唯一选项的问题
在Rails中执行此操作的一个简单方法是使用 validates_uniqueness_of
在您的模型中如下:
Question regarding 'unique' option
An easy way to do this in Rails is to use validates_uniqueness_of
in your model as follows:
validates_uniqueness_of :user_id, :scope => [:article_id]
这篇关于RoR中多列的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!