zoukankan      html  css  js  c++  java
  • mysql 前缀索引

    联合索引
    概念
    联合索引又叫复合索引,即一个覆盖表中两列或者以上的索引,例如:

    index_name(column a,column b)
    1
    创建方式
    执行alter table语句时创建
    alter table table_name add index index_name(column_list)
    1
    index_name是创建的联合索引的名字,可以没有,没有的话系统会根据该索引包含的第一列来赋名称;table_name是要创建该索引的表名;column_list为该索引所包含的表的字段名。

    执行create index语句时创建
    create index index_name on table_name(column_list)
    1
    此种情况是在表已经创建好的情况下,再来创建复合索引。index_name和column_list同上;table_name是要创建索引的表名。

    例子
    create table stu
    (
    id int,
    name varchar(10),
    age int,
    primary key(id)
    );
    ALTER TABLE stu ADD INDEX LianHeIndex (name,age);
    或者
    create index LianHeIndex on stu(name,age);
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    执行上面的语句后在表stu中就创建好了一个名叫LianHeIndex联合索引,在使用联合索引的时候,我们遵守一个最左原则,即INDEX LianHeIndex (name,age)支持name|name age组合查询,而不支持age查询;换句话说,在执行

    select * from stu where name=?
    1
    或者

    select * from stu where name=? and age=?
    1
    时联合索引才会有效,如果执行

    select * from stu where age=?
    1
    则联合索引不会生效。

    如果我们是在name和age上分别创建单个索引的话,由于mysql查询每次只能使用一个索引,所以虽然这样已经相对不做索引时全表扫描提高了很多效率,但是如果在name、age两列上创建复合索引的话将带来更高的效率。如果我们创建了(name, age)的复合索引,那么其实相当于创建了(name)、(name,age)两个索引,这被称为最佳左前缀特性。

    因此我们在创建复合索引时应该将最常用作限制条件的列放在最左边,依次递减。

    注意事项
    只要列中包含有NULL值都将不会被包含在索引中
    复合索引中只要有一列含有NULL值,那么这一列对于此复合索引就是无效的,所以我们在数据库设计时尽可能不要让字段的默认值为NULL。

  • 相关阅读:
    UVA 1386 Cellular Automaton
    ZOJ 3331 Process the Tasks
    CodeForces 650B Image Preview
    CodeForces 650A Watchmen
    CodeForces 651B Beautiful Paintings
    CodeForces 651A Joysticks
    HUST 1601 Shepherd
    HUST 1602 Substring
    HUST 1600 Lucky Numbers
    POJ 3991 Seinfeld
  • 原文地址:https://www.cnblogs.com/zpzp7878/p/12330325.html
Copyright © 2011-2022 走看看