SqlServer索引、优化、约束、连接

  1. 索引的创建和删除
  2. create index in_name on person(name)  --创建索引
    
    drop index person.in_name   --删除索引
         
    create index in_name_age on person(name,age)  --创建两个字段索引

    索引分为聚集索引和非聚集索引,

    1. 索引与表物理顺序一致,就是聚集索引,聚集索引只能有一个

    2. 索引与表物理地址不一致,就是非聚集索引 ,非聚集索引可以有多个

  3. 优化机巧:
    1. 对常用字段创建索引
    2. where子句尽量写在后面,如果有子查询先写子查询
    3. 使用参数化查询方式进行编程
    4. 需要查几个字段就写几个字段,不要全部用*
    5. 尽量少些sql,能简单实现的不要过多sql才实现
    6. 表连接效率高于exists和in关键字使用
    7. 一旦索引字段进行了计算,则会全表扫描,影响效率
    8. union all 效率比union高
  4. 非空约束: NOT NULL

  5. 单字段唯一约束:
  6. create table studentInfo(id int identity(1,1),name varchar(20) unique)
    
    insert into studentInfo values('kit')
    insert into studentInfo values('kit') --插入第二条时报错,提示定义唯一约束,不能插入重复

    多字段复合约束

  7. create table TeacherInfo(id int identity(1,1),Fnum int,FDep int,constraint FND unique(fnum,fdep)) -- FND为复合约束名

    表已存在,新增约束

  8. alter table studentinfo add constraint s1 unique(name)

    删除约束

  9. alter table teacherinfo drop constraint FND  --删除复合约束

    检查约束check

  10. alter table Person add check(age > 2)  --新增检查约束标识年龄必须大于2

    主键约束,主键后跟 primary key

  11. alter table studentinfo add constraint py primary key(id)  --新增主键约束
    alter table studentinfo drop constraint py  --删除约束

     外键约束

  12. create table Person(ID int identity(1,1),Name varchar(20),Age int,DepID nvarchar(20),primary key(id),foreign key(DepID) references DepMent(id))

     表连接

  13. --表连接
    
    select * from Person
    select * from Depment
    --内连接,默认只写一个join就是内连接
    select Person.name,Depment.depname from Person
    inner join Depment
    on Depment.id = Person.DepID
    where DepID = '001'
    
    --交叉连接:涉及到的表的所有记录都显示出来
    select p.Name,d.depname from Person p
    cross join Depment d
    
    --外部连接
    
    --左外连接:不管是否匹配成功,都会返回左边全部记录
    select p.Name,d.depname from Person p
    left outer join Depment d
    on p.depid = d.id
    
    --右外连接:返回右表全部数据,和左表匹配数据
    select p.Name,d.depname from Person p
    right outer join Depment d
    on d.id = p.DepID
    
    --全部外连接
    select p.Name,d.depname from Person p
    full outer join Depment d
    on d.id = p.DepID

转载于:https://www.cnblogs.com/micc/p/10642771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值