I have the following database structure:
- id
- name
- year
- director
- runtime
An example entry being: (1, "Titanic", 1994, "James Cameron", 02:44:00)
I want to find a match by any three of the four criteria, for example:
1. name + year + director
2. name + year + runtime
3. year + director + runtime
If I created one index, would that be sufficient for optimial queries?
ALTER TABLE myTable ADD INDEX (name, year, director, runtime)
Or, do I need to create an index for each combination?
ALTER TABLE myTable ADD INDEX (name, year, director)
ALTER TABLE myTable ADD INDEX (name, year, runtime)
ALTER TABLE myTable ADD INDEX (year, director, runtime)
I would obviously prefer to use the first, but which would be suggested here? Why would one be preferable to the other? This is an InnoDB table.
-
You could add a FULLTEXT index on all 4 columns and search with WHERE MATCH(all 4 columns) AGAINST (words) IN BOOLEAN MODEMihai– Mihai2016年03月11日 22:27:06 +00:00Commented Mar 11, 2016 at 22:27
-
@Mihai I'm using InnoDB.David542– David5422016年03月11日 22:27:55 +00:00Commented Mar 11, 2016 at 22:27
-
On 5.6 or higher you can use FULLTEXT on innoDBMihai– Mihai2016年03月11日 22:28:31 +00:00Commented Mar 11, 2016 at 22:28
1 Answer 1
Considering that id
is a primary key having default unique index; if you create one index with 4 columns that would be sufficient cause in that case what you are getting is a Covering Index
.
ALTER TABLE myTable ADD INDEX (name, year, director, runtime)
-
thanks for the explanation, could you please explain what a
Covering Index
is and how that's useful?David542– David5422016年03月11日 22:22:10 +00:00Commented Mar 11, 2016 at 22:22 -
1A covering index refers to the case when all fields selected in a query are covered by an index, in that case InnoDB (not MyISAM) will never read the data in the table, but only use the data in the index, significantly speeding up the select.Reto– Reto2016年03月11日 22:23:46 +00:00Commented Mar 11, 2016 at 22:23
-
1@David542, see this SO thread stackoverflow.com/questions/8213235/… as well as MySQL docs dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.htmlRahul– Rahul2016年03月11日 22:26:55 +00:00Commented Mar 11, 2016 at 22:26
-
2This search
year + director + runtime
wont use your indexMihai– Mihai2016年03月11日 22:31:10 +00:00Commented Mar 11, 2016 at 22:31 -
@Mihai why wouldn't it?David542– David5422016年03月11日 22:34:54 +00:00Commented Mar 11, 2016 at 22:34