views:

487

answers:

1

I need to speed up a query. Is an index table what I'm looking for? If so, how do I make one? Do I have to update it each insert?

Here are the table schemas:

--table1--   |   --tableA--   |    --table2--
id           |   id           |    id
attrib1      |   t1id         |    attrib1
attrib2      |   t2id         |    attrib2
             |   attrib1      |

And the query:

SELECT 
  table1.attrib1, 
  table1.attrib2,
  tableA.attrib1 
FROM 
  table1,
  tableA
WHERE 
  table1.id = tableA.t1id
  AND (tableA.t2id = x or ... or tableA.t2id = z)
GROUP BY 
  table1.id
+4  A: 

You need to create a composite index on tableA:

CREATE INDEX ix_tablea_t1id_t2id ON table_A (t1id, t2id)

Indexes in MySQL are considered a part of a table: they are updated automatically, and used automatically whenever the optimizer decides it's a good move to use them.

MySQL does not use the term index table.

This term is used by Oracle to refer to what other databases call CLUSTERED INDEX: a kind of table where the records themselves are arranged according to the value of a column (or a set of columns).

In MySQL:

  • When you use MyISAM storage, an index is created as a separate file that has .MYI extension.

    The contents of this file represent a B-Tree, each leaf containing the index key and a pointer to the offset in .MYD file which contains the data.

    The size of the pointer is determined by the server setting called myisam_data_pointer_size, which can vary from 2 to 7 bytes, and defaults to 6 since MySQL 5.0.6.

    This allows creating MyISAM tables up to 2 ^ (8 * 6) bytes = 256 TB

  • In InnoDB, all tables are inherently ordered by the PRIMARY KEY, it does not support heap-organized tables.

    Each index, therefore, in fact is just a plain InnoDB table consisting of a single PRIMARY KEY of N+M records: N records being an indexed value, and M records being a PRIMARY KEY of the main table record which holds the indexed data.

Quassnoi