SQL基本语句

来源:互联网 发布:软件开发工作量统计表 编辑:程序博客网 时间:2024/06/04 18:54
---添加数据
--insert into 表名(字段列表) values(值列表)
insert into teacher(tname,tgender,tidcard,ttelephone) 
values('老王',default,'123456789123456789','32154672')

--修改数据
--update 表名 set 列名=值,列名2=值2... <where 条件>
--修改老王老师的联系电话
update teacher set ttelephone='987654' where tid=10004
--修改所有性别是女生的家庭地址改为‘北京奥运村’
update student set address='北京奥运村' where gender='女'

--删除数据
--delete from 表名 <where 条件>
--删除老王老师的数据
delete from teacher where tid=10004

--截断数据
--truncate table 表名

--查询数据
--select 列名 from 表名
-- <where 条件 order by 排序列名 desc/asc group by 分组列名 having 分组后条件筛选>

--查询表的全部数据
select * from teacher
--查询所有男老师的数据
select * from teacher where tgender='男'
--使用AS 起别名,使用常量添加新列,查询部分列
select 学校='中软ETC',tname 老师姓名,ttelephone 联系电话 from teacher
--使用字符串拼接
select 老师信息='老师姓名:'+tname+',联系电话:'+ttelephone from teacher

--查询某个字段为NULL的数据
select * from teacher where ttelephone is not null

--查询表结构不需要展示数据
select * from teacher where 1<>1

--查询考试成绩最高的前五名成绩
select top 5 score from score order by score desc

select getdate()

--查询今天开班的班级信息
select * from tclass where datediff(dd,cdate,getdate())=0

--修改所有密码O改为0,I改为1
update set password=replace(replace(password,'O','0'),'i','1')

--使用LIKE 查询所有姓张的老师
select * from teacher where tname like '张%'

--查询考试成绩60分到70分的成绩数据
select * from score where score>=60 and score<=70
select * from score where score between 60 and 70

--查询所有是福建省或江西省的学生信息
select * from student where state='福建省' or state='江西省'
select * from student where state in ('福建省','江西省')

--查询所有在1班或2班的学生信息
select * from studnet where classid=1 or classid=2
select * from studnet where classid in (1,2)

--聚合函数:sum,avg,count,max,min

--查询所有考试成绩的平均分、总分、参加考试的人数,最高分、最低分
select sum(score) 总分,avg(score) 平均分,count(*) 人数,max(score) 最高分,
min(score) 最低分 from score

--查询每一门考试成绩的平均分
select courseid,avg(score) from score group by courseid

--多表连接查询
--查询所有班级信息以及带班老师的姓名和联系电话
select a.*,b.tname,b.ttelephone from tclass a inner join teacher b on(a.tid=b.tid)

select a.*,b.tname,b.ttelephone from tclass a,teacher b where a.tid=b.tid

--查询所有老师的信息以及他所带班的班级名称,如果没带班也要显示
select a.*,b.cname from teacher a left join tclass b on (a.tid=b.tid)
0 0