码迷,mamicode.com
首页 > 数据库 > 详细

SQL -- 索引

时间:2015-08-09 12:13:52      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

SQL – 索引

SQL – 索引

primary key

  create table user2 (
  id int PRIMARY KEY,
  username varchar(20)
  );
  show tables;
  drop table user2;

create table user2 (
  id int,
  username varchar(20),
  PRIMARY KEY (id)
  );
  drop table user2;

auto_increment

auto_increment 必须用在 primary_key 上

create table xxx (
id int(10) unsigned primary key auto_increment,
) auto_increment=1;                  # 表示从 1 开始计算

unique

防止重复, 一般是注册用户名, 用户邮箱等

create table test1 (
id int unsigned unique,
username varchar(30) not null
);
drop table test1

index 普通索引

create index INDEX_NAME on TABLE_NAME (COLUMN) using btree;  # 默认是 btree, 可以是 hash
alter table TABLE_NAME add index INDEX_NAME (COLUMN)

多列索引

alter table TABLE_NAME add index INDEX_NAME (COLUMN1, COLUMN2, COLUMN3)
drop index INDEX_NAME on TABLE_NAME

备注: COLUMN 如果是 text 类型, 必须指定 length, COLUMN(length), 使用长度还可以优化查找效率

索引的使用场景:

where ... LIKE ‘xxx%‘;
where ... LIKE ‘%xxx‘;    # 不会使用索引

索引大大提高了查询速度, 也会降低更新表的速度, insert, update 和 DELETE. 更新表时, MySQL 不仅要保存数据, 还要保存索引文件

全文索引

alter table TABLE_NAME add fulltext (COLUMN)

default

default 就是插入的时候不指定值的时候自动赋予的值

create table time1 (
tm timestamp unique default now(),
username varchar(30)not null
);
drop table time1;

SQL -- 索引

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4714802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!