索引和视图

索引优点:
1,一般是作用于where子句所给出的条件相匹配的行
一是在关联操作中与其他数据表所匹配的行。
2,对于使用mix() 和max()函数的查询的列
3,经常使用order by 和group by的列
4,索引可以加快查询速度,不用扫描整个表
索引缺点
1,索引虽然加快查询的速度,但是会降低写入操作,比如插入,修改,删除数据
2,索引要占据磁盘空间,索引越多占据空间越大,
 
对myisam表来说,大量索引一个数据表可能使索引文件比数据文件更快达到它的尺寸上限
对innodb来说,全部innodb数据表分享同一个存储空间,添加索引会是表空间用于存储的空间变小
 
散列索引对于“=”和“<=>”操作进行匹配时速度极快,但是对于范围查找和比较查找比较慢
 
B树索引对于 <,<=,>,>=,=<>,!= 和 between操作进行的查询效率较高,而且对于纯字符串开头,而不是通配符开头的,B树可以使用like操作符进行模式匹配
 
慢查询
mysqldumpsqlow
 
1,主键索引
2,唯一索引
3,常规索引
 
4,全文索引
创建索引,默认是asc排序,使用btree
create  index  index_name   on  tbl_name (column  asc{default}|desc) 
如果相关表已经使用Memory引擎建立,则使用hash索引
create index  index_name  using btree|hash   on   on  tbl_name (column  asc)
创建复合索引
create  index  index_name  on tbl_name  (column1,column2)
 
create table carts(
cartid int not null,
userid,
bookid,
number,
primary key (cartid),
key index_name(userid,bookid)
);
唯一索引
create  unique  index  index_name  on tbl_name  (column)
可选项:unique |fulltext | spatial
create table cate(
    cateid int not null auto_increment primary key,
    catename varchar not null unique
    catemenu varchar not null fulltext
);
使用alert语句添加索引
alert table tbl_name  add index index_name using btree  (column)
 
创建表时添加索引
create  table tbl_name(
column1  int  not null primary key,
column2   int not null,
column3    smallint not null,
index  index_name(column)
unique  indxe index_name using hash (column2,column3)
)
全文索引
全文搜索同MATCH()函数一起执行。 

mysql> CREATE TABLE articles ( 

 id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, 

 title VARCHAR(200), 

 body TEXT, 

FULLTEXT (title,body) 

); 
1,任何过于短的词都会被忽略。 全文搜索所能找到的词的默认最小长度为 4个字符。 
2,停止字中的词会被忽略。禁用词就是一个像“the” 或“some” 这样过于平常而被认为是不具语义的词。存在一个内置的停止字, 但它可以通过用户自定义列表被改写。 
3,单词  出现在50%的行中。 它被列入停止字。
select book_name ,price from books where Match(column) against("string"); 
 
drop index  index_name on tbl_name
 
 
视图
视图是一种虚拟表,他的行为和数据表一样,但是不包含真正的数据。
创建视图语法
create view  <view name>[<column list>]   as   <table expression>  [with [cassaded | local ] check option]
创建视图
create  view  view_name  as  select  column1,column2  from tbl_name  where   xxx>xx
创建视图时指定列
create  view  view1 (va1,va2,va3)  as  select  va1,va2,va3 from tbl  where  va1<num;
创建索引时可以使用表联接
creaet  view  vst as select id,name,date,score category from grade_event inner  join  score  inner join  stu  on  grade_event.id=score.event_id and score.id =stu.id
创建索引时可以把数学运行放到视图的一个 列中
create    view view_demo  select  name,   birth,death timstampdiff(year,birth ,death) as age from tbl
posted @ 2013-01-14 20:00  fsl  阅读(4888)  评论(0编辑  收藏  举报