gpt4 book ai didi

mysql - 如何在 Rails 中正确指定多列索引

转载 作者:可可西里 更新时间:2023-11-01 06:34:37 24 4
gpt4 key购买 nike

如本题所示: How do I make a column unique and index it in a Ruby on Rails migration?
你可以这样写:

add_index :the_table, [:foo_column, :bar_column], unique: true

添加多列索引。
但是是否仍然需要为您已经指定多列索引的那些列中的每一列添加单个索引?

我的意思是像在上面显示的代码之外编写下面的代码

add_index :the_table, :foo_column  
add_index :the_table, :bar_column

最佳答案

对于 MySQL:

MySQL 将能够使用索引 [:foo_column, :bar_column] 来查询两列的条件,也可以只查询左列的条件,而不是右列。

更多信息在这里:http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html

所以你应该这样做

add_index :the_table, [:foo_column, :bar_column], :unique => true
add_index :the_table, :bar_column

确保正确索引所有内容

MySQL 从左到右对列进行索引,因此如果您有一个像这样的多列索引:[:col1, :col2, :col3, :col4],您可以在:

  • col1
  • col1 + col2
  • col1 + col2 + col3
  • col1 + col2 + col3 + col4

所以你可以查询最左边的列

如果您还需要其他任何东西,则必须创建更多索引

同样,这仅适用于 MySQL,postgres 可能会有所不同

关于mysql - 如何在 Rails 中正确指定多列索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com