站点图标 久久日记本

SQL基础复习(1)

1、表上的对象

--字段:数据库表网格中的一列,又称column
--记录:数据库表网格中的一行,又称row
--主键:一个表中能唯一区分每一条记录的字段,它可以做为其他表的外键
--外键:一个表中的某个字段的取值是另一个表的主键
--唯一键:一个表中能唯一区分每一条记录的字段,不能做外键

--索引:根据表的某些字段将数据进行分组,目的是提高查询效率,
--但是会导致新增等操作的效率降低,创建索引的字段取值不能很多
--索引适用于一些频繁进行查询的表,对于频繁进行新增等操作的表不适宜创建索引

2、新建表

create table Person1
(
 ID int not null identity(1,1) primary key,
 Name varchar(20),
 Age int,
 Sex char(2)
)

drop table person1

alter table person add birthday datetime
alter table person1 drop column Birthday

--删除数据用delete,删除数据库对象用drop

3、查询数据

select ID,Name,Birthday,Salary from Person
select ID,Name,year(Birthday),Salary+10000 from Person
--select 后面的字段可以是表的字段,也可以是计算公式,还可以是方法等

select * from person
select * from person order by salary asc--desc降序,asc升序
select * from person order by classID asc,salary desc
select distinct salary from person--消除重复行
select distinct sex,salary from person

--条件查询
select * from person where ID = 5
select * from person where salary >= 3000
select * from person where sex != '女'
select * from person where sex <>'女'
select * from person where not ID=5--not表示取反

select * from person where salary between 1000 and 3000--包含两个边界值
select * from person where id in (2,4,6,8,10,100)

select * from person where name like 'hu%'--通配符%表示任意个任意的字符, _表示一个任意的字符
select * from person where name like '%hu%'

select * from person where  sex is null--查询 null值的数据用is

--多条件查询
select * from person where classID=1 and sex='女' and birthday >'1985-1-1'
select * from person where classID=1 or sex='女' 
select * from person where  sex='女' and (birthday>'1985-1-1' or classID=1 )--and和or一起使用的时候,用()限定执行先后顺序


--聚合函数
select max(salary) from person--最大值
select min(salary) from person--最小值
select avg(salary) from person--平均值
select sum(salary) from person--总和
select count(*) from person--取记录的数量


--分组查询:根据字段的值将数据进行分组,得到的结果是每个分组的计算结果
--select查询的字段只能是分组的条件或者聚合函数
select count(*),classID
from person
group by classID

select classID
from person
where sex='女'--where用于限定所有的数据的条件
group by classID
having count(*)>=3--having用于限定分组内的条件,一般都只是聚合函数

4、更新数据

--修改
update Person set
 sex='女',
 salary = 3000.0
where id = 10

--注意两表关联更新的情况

5、删除数据

--删除
delete from Person
where id=9

--删除一个表中重复的数据???
注:2018-08-30 删除Person表中id等于9的数据,不论重复问题

6、数据类型

--char:固定长度字符串,如果输入字符不足,后面添空格
--varchar:不固定长度的字符串

--int:整数
--numeric:数值类型,可以小数,可以整数,表达方式numeric(20,2)

--datetime:表示时间 yyyy-mm-dd HH:mi:ss(24h)
insert into Person(ID,Name,Sex,Birthday,Salary)
values(1,'huqitao','m','2000-1-1',4000.0)

--数值类型的值不需要加单引号,时间类型和字符串需要加上单引号

7、新增数据

--新增
insert into Person(Name,Sex,Birthday,Salary)
values('Hello','f','1990-2-2',4000.0)

insert into Person(Name,sex,birthday,salary)
select name,sex,birthday,salary from person where sex='女'


--复制表
select * into Person2 from person
退出移动版