如果使用唯一键,使用MYSQL是各个字段所需的密钥?

时间:2014-03-02 23:13:49

标签: mysql indexing

我有一个简单的链接表,请参阅下面的create sql 我的问题是,我是否需要为amtw_propnameid_idx设置单独的索引,如果我有amtw_u1则需要amt_amt_concept_id_idx? 我使用此表来连接和过滤amtw_propnameid和amtw_amt_concept_id。我使用唯一索引来强制执行限制,即两行不能相同。

    $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.';";

1 个答案:

答案 0 :(得分:1)

索引只能用于优化使用最左列的查询;正如巴里 - 约翰逊评论的那样,

  

如果表有多列索引,则表示最左边的前缀   优化器可以使用index来查找行。例如,如果你   在(col1,col2,col3)上有一个三列索引,你已编入索引   搜索(col1),(col1,col2)和(col1,col2,col3)的功能。

     

如果列不形成最左边的前缀,则MySQL无法使用索引   的索引。假设您有SELECT语句:

     

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;

     

如果(col1,col2,col3)上存在索引,   只有前两个查询使用索引。第三和第四个查询   确实涉及索引列,但(col2)和(col2,col3)不是   最左边的前缀(col1,col2,col3)。

See the mysql documentation for more info