SQLServer第九章:视图与索引

视图:查看来自于一个或多个列的列的集合,一张虚拟表,视图中并不存放任意数据,只存放select语句
   查看视图最基本的代码:select * from 表名 返回一个虚拟表

索引:提高查询速度/性能,可以理解为索引就是目录,找到他那一页的数据。

分类:
  (1)主键索引:创建了主键就会自动创建主键索引,是唯一索引的特殊类型
  (2)唯一索引[unique]:不能重复
  (3)非聚集索引[nonclustered]:创建索引页,索引页上注明了值存放的位置,一个表最多可以有249个非聚集索引
  (4)聚集索引[clustered]:会进行物理排序,一个表最多只有一个聚集索引
索引命名:index_表名_列名

--sys.databases:数据库
--sys.objects:表,视图,存储过程
--sys.indexes:索引

 创建 一个表做演示

复制代码
if exists(select * from sys.objects where name='accountInfo')
begin
    drop table accountInfo
end
go
create table accountInfo
(
    id int primary key identity,
    accountName varchar(10) not null,
    balance money check(balance>=1) not null
)
go
--添加两个帐户
insert into accountInfo values('韦小宝',5000000)
insert into accountInfo values('梅超风',6000000)
go
select * from accountInfo
复制代码

在用户名上创建一个【唯一索引】

复制代码
if exists(select * from sys.indexes where name='index_userinfo_username')
begin
    drop index accountInfo.index_userinfo_username --删除必须是:表名.索引名
end
go
create unique index index_userinfo_username  --创建 唯一 索引 取名称
on accountInfo(accountName)    --表名(列名)
go

--测试索引效果:
insert into accountInfo values('admin','123456')
复制代码

在姓名上创建一个【非聚集索引】

复制代码
if exists(select * from sys.indexes where name='index_stuinfo_stuname')
begin
    drop index accountInfo.index_stuinfo_stuname
end
go
create nonclustered index index_stuinfo_stuname
on accountInfo(accountName)
go
--with(index=index_stuinfo_stuname):可选,特别是只有一个索引完全可以省略
select * from accountInfo with(index=index_stuinfo_stuname) where accountName='admin'
复制代码

 

posted @   Akai_啊凯  阅读(142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示