Question

I have a simple linking table, see the create sql below.
My question is, do i need to have the individual indexes for amtw_propnameid_idx, and amt_amt_concept_id_idx if i have amtw_u1? I use this table to join and filter on both amtw_propnameid and amtw_amt_concept_id. I use the unique index to enforce the restriction that no two rows can be identical.

    $sql= "CREATE TABLE `refset_amt_webster` (
    amtw_id int unsigned not null AUTO_INCREMENT,
    amtw_propnameid int null default null comment 'links to the Webster proprameid drugs table',
    amtw_amt_concept_id bigint not null comment 'links to the AMT concept id',
    amtw_disabled tinyint unsigned not null default 0 comment '1=disabled',
    PRIMARY KEY(amtw_id),
    KEY amtw_propnameid_idx (amtw_propnameid),
    KEY amtw_amt_concept_id_idx (amtw_amt_concept_id),
    UNIQUE KEY amtw_u1 (amtw_propnameid,amtw_amt_concept_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT 'AMT to MIMS linking table.';";
Was it helpful?

Solution

Indexes can only be used to optimize queries which use leftmost columns; as barry-johnson commented,

If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).

MySQL cannot use an index if the columns do not form a leftmost prefix of the index. Suppose that you have the SELECT statements shown here:

SELECT * FROM tbl_name WHERE col1=val1;

SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

SELECT * FROM tbl_name WHERE col2=val2;

SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3).

See the mysql documentation for more info

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top