MySQL 综合实例 Petstore7.5 索引
为Petstore数据库建立相关索引
(1)使用create index 创建索引
1、对account 表中的email列按降序创建普通索引I_em_ind
create index I_em_ind on account(email desc);
2、对account表中的fullname 和address列创建复合索引C_fa_ind
create index C_fa_ind on account(fullname,address);
3、对product 表中的name 列前4个字创建唯一性索引U_na_ind
create unique index U_na_ind on product(name(4));
(2)使用Alter Table添加索引
1、对category表中的caid列创建主键索引,catname列添加一个唯一索引U_ca_ind
alter table category add unique U_ca_ind(catname);
🌟因为之前创建表的时候我们已经创建过主键了,所以在这里无需为列再添加主键索引,如果重复添加,则会报错1068—Multiple primary key defined。
2、对lineitem表中的orderid 和itemid 列创建主键索引,quantity和unitcost列添加一个复合索引C_qu_ind
alter table lineitem add index C_qu_ind(quantity,unitprice);
🌟因为之前创建表的时候我们已经创建过主键了,所以在这里无需为列再添加主键索引,如果重复添加,则会报错1068—Multiple primary key defined。
3、对account 表中的userid 列创建主键索引,fullname列创建唯一索引U_fa_ind
alter table account add unique U_fa_ind(fullname);
🌟因为之前创建表的时候我们已经创建过主键了,所以在这里无需为列再添加主键索引,如果重复添加,则会报错1068—Multiple primary key defined。
(3)创建表的同时创建索引
1、创建购物车表shopcat(购物车编号shopcaid,客户编号userid,商品编号itemid,单价quantity,数量unitprice),并对购物车编号创建主键,在客户编号和商品编号列上创建复合索引C_up_ind
create table shopcat(shopcatid int(11) not null primary key,userid char(10) not null,itemid char(10) not null,quantity int(11) not null,unitprice decimal(10,2) not null,index C_up_ind(userid,itemid));
2、显示shopcat表的索引情况。
show index from shopcat;
3、删除shopcat表上的C_up_ind索引
drop index C_up_ind on shopcat;