在MySQL中查询多列索引表

时间:2017-04-26 11:19:24

标签: mysql

我有一个MySQL表,其中包含一个包含3列的索引: colA,ColB,ColC

如果我这样做一个查询:

SELECT * FROM MyTable WHERE colA='some value' AND colB = 'some other value'

是否使用了索引或是否需要使用colA和colB

创建单独的索引

1 个答案:

答案 0 :(得分:0)

DROP TABLE IF EXISTS my_table;


CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,dense INT NOT NULL
,sparse INT NOT NULL
, other INT NOT NULL
, INDEX(dense,sparse,other)
);

INSERT INTO my_table VALUES (1,1,1,1);

INSERT INTO my_table (dense,sparse,other) SELECT RAND()*10,RAND()*1000000,RAND()*1000 FROM my_table;

-- Repeat last command 10 times, or so...


EXPLAIN SELECT * FROM my_table WHERE dense = 9 AND sparse = 1000;
+----+-------------+----------+------+---------------+-------+---------+-------------+------+-------+
| id | select_type | table    | type | possible_keys | key   | key_len | ref         | rows | Extra |
+----+-------------+----------+------+---------------+-------+---------+-------------+------+-------+
|  1 | SIMPLE      | my_table | ref  | dense         | dense | 8       | const,const |    1 |       |
+----+-------------+----------+------+---------------+-------+---------+-------------+------+-------+
1 row in set (0.00 sec)

EXPLAIN SELECT * FROM my_table WHERE sparse = 1000;
+----+-------------+----------+------+---------------+------+---------+------+-------+-------------+
| id | select_type | table    | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+----+-------------+----------+------+---------------+------+---------+------+-------+-------------+
|  1 | SIMPLE      | my_table | ALL  | NULL          | NULL | NULL    | NULL | 16384 | Using where |
+----+-------------+----------+------+---------------+------+---------+------+-------+-------------+
1 row in set (0.00 sec)