LoginSignup
6
5

More than 1 year has passed since last update.

mysql index 検証② force indexを使用

Last updated at Posted at 2018-01-12

続き。

| data5 | CREATE TABLE `data5` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` tinyint(1) NOT NULL,
  `name` varchar(50) NOT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_1` (`status`),
  KEY `idx_2` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=4194305 DEFAULT CHARSET=latin1

idx_1 (status)、idx_2 (name) それぞれインデックスが存在する。
force indexで強制的に使用するインデックスを指定してあげると
ただしくインデックスが張られていても、使用されない。

mysql> explain  select * from data5 force index(idx_1) where name = "test000000000";
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
|  1 | SIMPLE      | data5 | ALL  | NULL          | NULL | NULL    | NULL | 4165246 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)
mysql> explain  select * from data5 force index(idx_2) where name = "test000000000";
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------+
| id | select_type | table | type | possible_keys | key   | key_len | ref   | rows | Extra                 |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------+
|  1 | SIMPLE      | data5 | ref  | idx_2         | idx_2 | 52      | const |    1 | Using index condition |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------+
1 row in set (0.00 sec)

以前の対応した案件では、1億レコード近いデータから対象のデータを取得する時
性能劣化により、インデックスが使用されないという事態が発生しました。
その際、force indexを使用する事で解決できました。

6
5
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
6
5