LoginSignup
0
0

More than 5 years have passed since last update.

Rails unique とindexの違い

Posted at

やりたかったこと

nameをuniqueにして、indexを貼り
高速でtagの情報を読み取りたかった。

疑問

下記の行のname_uniqueとname_indexが
ridgepole export 時にできたので
この違いはなにかと疑問に思った。

環境

Schemafileの作成方法は

MysqlWork Branch -> Mysql -> ridgepole export

create_table "tags", id: :integer, unsigned: true, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
  t.string "name", limit: 45, null: false
  t.datetime "updated_at", null: false
  t.datetime "created_at", null: false
  t.index ["name"], name: "name_UNIQUE", unique: true
  t.index ["name"], name: "name_index"
end

Work banch

スクリーンショット 2017-05-15 11.32.26.png

スクリーンショット 2017-05-15 11.32.33.png

explain

mysql> explain  select * from tags where name = 'vhtfdy'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tags
   partitions: NULL
         type: const
possible_keys: name_UNIQUE,name_index
          key: name_UNIQUE
      key_len: 137
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

ERROR:
No query specified

 結論

explainの結果を見るとオプティマイザーは
name_UNIQUE,name_indexの二つのindexを候補に出して、
name_UNIQUEを使用している。
そして typeconstで最速である。

name_index使用した場合(下記参照)は


mysql> explain  select * from tags force index (name_index) where name = 'vhtfdy'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tags
   partitions: NULL
         type: ref
possible_keys: name_index
          key: name_index
      key_len: 137
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

ERROR:
No query specified

mysql>

typerefになり、indexが効いているとは言えるが
constのほうが早いため、

name_indexは必要ない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0