数据库基础二

1:sql约束

a:主键约束 primary key(列名)

两种写法:id int not null primary key或constraint 约束名字    primary key(id,name)

建完表再增加:alter table 表名 add primary key(id)或alter table 表名 add constraint 约束名字  primary key(id,name)

撤销主键约束:alter table 表名  drop primary key或 alter table 表名  drop constraint 约束名字

b:唯一性约束:要求表里面的某个字段的值在每条记录里是唯一的

两种写法:name varchar(50) null unique或者constraint 约束名字   unique(name,age)

建完表再增加:alter table 表名 add unique(name)或alter table 表名 add constraint 约束名字   unique(name,age)

撤销unique约束:alter table 表名  drop index 约束名字    或alter  table 表名  drop  constraint 约束名字

c:外键约束

两种写法:主表主键  int foreign key references 主表(主表主键) 或constraint 外键名称  foreign key(主表主键) references 主表(主表主键)

建完表再增加:alter table 表名 add foreign key(主表主键) references 主表(主表主键) 或alter table 表名  add constraint 约束名字  foreign key(主表主键) references 主表(主键主表)

撤销外键约束:alter table 表名  drop constraint 约束名称

d:not null约束
例如:name varchar(50) not null,

e:检查约束(限制列中值的范围),如果对单个列定义check约束,那么该列只允许特定的值,如果对一个表定义check约束,那么此约束会在特定的列中对值进行限制

两种写法:id int not null check(id>0)或constraint 约束名称 check(id>0 and name='zhangSan')

建完表再增加:alter table 表名 add check(id>0)或 alter table 表名 add constraint 约束名称  check(id>0 and name='张三')

撤销check约束:alter table 表名 drop constraint 约束名称

2:算数操作符

加法+: select 列1 + 列2 from 表名  或   select 列1 from 表名  where  列1+列2>'4000'

减法-: select 列1 - 列2 from 表名  或   select 列1 from 表名  where  列1-列2>'4000'

乘法*: select 列1 * 10 from 表名    或    select 列1 from 表名  where   列1*10>'4000'

除法/: select 列1 / 10 from 表名    或    select 列1 from 表名  where (列1/10)>'4000'

3:汇总函数

使用count(*)统计表里面的数量: select count(*) from 表1  或  select count(distinct 列名) from 表1

使用sum函数统计一组记录中某一个字段的总和: select sum(列1) as t from 表1  或  select sum(distinct 列名) from 表1

使用avg函数统计一组记录的平均值: select avg(列1) as t from 表1  或  select avg(distinct 列名) from 表1

使用max函数返回一组记录的某个字段的最大值: select max(列1) as t from 表1  或  select max(distinct 列名) from 表1

使用min函数返回一组记录的某个字段的最小值: select min(列1) as t from 表1  或  select min(distinct 列名) from 表1

4:group by子句(与select语句配合使用,把相同的数据划分为组,在select语句里,group by子句在where子句之后,在order by子句之前)

只有被选中的字段(即select后面的字段)才能在group by子句里面引用,如果字段在select语句里面找不到,就不能用于group by子句

select 列1,列2 from 表名 group by 列1,列2  或  select 列1,sum(列2) from 表名 group by 列1,列2

不能在视图中使用order by语句

5:having子句(having子句在select语句里与group by子句联合查询使用,用于告诉group by子句在输出里包含哪些分组)

Having子句必须跟在group by子句之后,在order by子句之前: select 列1,列2 from 表名 where 条件 group by 列1,列2 having 条件 order by 列1,列2

猜你喜欢

转载自blog.csdn.net/xhf852963/article/details/78922871