【第二阶段 | MySQL高级应用=索引-视图】

创建时间: 2021/4/17 22:15
更新时间: 2021/4/17 22:19
作者: 云雲

【第二阶段 | MySQL高级应用=索引-视图】 - 图1

— 索引

— 主键索引 primary key

— 创建表时添加主键索引

create table test_index( did int primary key, dname varchar (20), hobby varchar(30));

— 修改表结构添加主键索引,不需要可以添加,设置了主键就可以

— alter table 表名 add primary key(列名) alter table test_index add primary key(did);

— 唯一索引 unique

create unique index unique_index_hobby on test_index(hobby); INSERT INTO test_index VALUES(1,’张三’,’DBJ’); INSERT INTO test_index VALUES(2,’张2’,’DBJ’);
-- 报错会提示已经设置了唯一索引,唯一索引提高了效率和保证了数据的唯一性

— 普通索引 normal index

create index index_dname on test_index(dname); — 创建单列索引 alter table test_index drop index index_dname; — 删除索引 create index index_dname_hobby on test_index(dname,hobby); — 复合索引 针对where使用


— 视图

— 需求 查询各个分类下的商品平均价格

— 使用left join, select cname, avg( price ) from category_products_view group by cname; — 子查询封装为视图 CREATE VIEW category_products_view AS SELECT * FROM products p LEFT JOIN category c ON p.category_id = c.cid

— 需求 查询鞋服分类下最贵商品的全部信息

— 通过连表查询 — 先求出鞋服分类下的最高商品价格 select max(price) from products p LEFT JOIN category c on p.category_id =c.cid where cname=’鞋服’; — 把最高价格+鞋服分类最为条件在关联查询中应用获取对应商品的全部信息 select * from category_products_view where cname=’鞋服’ and price=(select max(price) from category_products_view where cname=’鞋服’);